Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Errors and Debugging : 10

    • Functions : 9

    • Practice with Loops and Algorithms : 8

    • Algorithms I : 7

    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Functions

    fun searchArray(values: IntArray, lookingFor: Int): Boolean {
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    return true
    }
    }
    return false
    }
    var example = intArrayOf(1, 9, 9)
    println(searchArray(example, 9))
    println(searchArray(example, 4))

    In this lesson we’ll learn how to package up our code into reusable pieces called functions.

    Along with implementing new algorithms and exploring new data structures, we’ll also explore new ways of structuring our programs in future lessons. Functions—also called methods or subroutines—are the basic structural building blocks of computer programs.

    Important note: we’re charging forward in our exploration of Kotlin. Functions are such an important idea that it’s worth getting a bit ahead of ourselves. Starting tomorrow we’re going to slow down, practice what we’ve already learned, and integrate. Put another way: tomorrow’s lesson is shorter!

    Why Functions?
    Why Functions?

    Let’s return to the search algorithm that we presented in the last lesson:

    var values = intArrayOf(1, 9, 9)
    var lookingFor = 9
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    println("Found!")
    break
    }
    }

    This is a nice example of solving one specific problem: search for the value contained in lookingFor in the array values. But what if I wanted to also look for another value in a second array? I could do this:

    var values = intArrayOf(1, 9, 9)
    var lookingFor = 9
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    println("Found!")
    break
    }
    }

    This works fine. But there’s a problem: we have duplicated our algorithm now in two places! We could do this, and continue copy-and-pasting our search algorithm wherever we needed it in our code. But a better strategy is to refactor our code so that we can reuse the algorithm in multiple places.

    Functions
    Functions

    Just like we did with algorithm, let’s carefully parse the Wikipedia definition of function:

    In computer programming, a subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.

    Now let’s consider how to convert the code for our search algorithm into a function.

    var values = intArrayOf(1, 9, 9)
    var lookingFor = 9
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    println("Found!")
    break
    }
    }

    To make this code reusable, our goal is to rewrite it so that it can look for any Int value in any IntArray. To do this, we need to separate the algorithm that can be reused from the inputs that can vary. Let’s walk through how to do that:

    var values = intArrayOf(1, 9, 9)
    var lookingFor = 9
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    println("Found!")
    break
    }
    }

    Anatomy of a Function
    Anatomy of a Function

    The walkthrough above identified two of the required parts of a function. First, we need the code that we’re going to reuse. Second, we need to identify the data or inputs that are provided to that code.

    There are two additional requirements. Third, each function needs a name so that we can identify it when it is reused. Fourth, functions need some way of returning a result—in our example, whether or not the value was found or not.

    These set of requirements lead us to our first function definition. Let’s go through each part of it carefully together:

    fun searchArray(values: IntArray, lookingFor: Int): Boolean {
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    return true
    }
    }
    return false
    }

    Calling Functions
    Calling Functions

    We call executing the reusable logic that a function encapsulates calling that function. To call a function, we need to identify it using its name and provide the inputs that it needs to complete the task. Let’s go through calling our search function and several different ways that we can use the result:

    fun searchArray(values: IntArray, lookingFor: Int): Boolean {
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    return true
    }
    }
    return false
    }

    Function Arguments
    Function Arguments

    Part of how we make functions reusable is by having them accept arguments. For example, this function does implement a search, but it’s not particularly useful:

    fun searchArrayForFour(values: IntArray): Boolean {
    for (i in values.indices) {
    if (values[i] == 4) {
    return true
    }
    }
    return false
    }

    In this case searchArrayForFour is a perfectly valid algorithm for search an array, but only for the value 4. What if we want to search for 5, or 8? We don’t want to have to write a separate search function for each value we might want to look for!

    Instead, as we see above, we let the value that we are looking for be a parameter that is provided to the function by the caller. This allows us to search for any value, not just a specific value. In the walkthrough below we talk a bit more about function arguments and compare them to the variable declaration and initialization we’ve seen previously.

    fun searchArray(values: IntArray, lookingFor: Int): Boolean {
    for (i in values.indices) {
    if (values[i] == lookingFor) {
    return true
    }
    }
    return false
    }

    return and Return Type
    return and Return Type

    Our new bit of Kotlin syntax in this lesson is the return statement. return causes a function to immediately stop and return or yield a value:

    fun subtractOne(value: Int): Int {
    return value - 1
    }
    println(subtractOne(3))
    fun divideByTwo(input: Double): Double {
    return input / 2.0
    }
    var smaller = divideByTwo(7.0)
    println(smaller)

    The return value must match the return type of the method, which is part of the method declaration. And every function must return a value of the type declared. For example, this doesn’t work:

    fun isPositive(value: Int): Boolean {
    if (int > 0) {
    return true
    } else if (int < 0) {
    return false
    }
    }

    Practice: Add One Function

    Created By: Geoffrey Challen
    / Version: 2020.8.0

    For this homework you'll write a simple function, a reusable piece of code that allows us to build more complex computer programs.

    We're going to start simple. Declare and implement a function called addOne. Your function should accept a single Int argument and return the result of adding one to its argument.

    return Is Not println
    return Is Not println

    We’ll continue using println to trace the execution of our programs as they run. But it’s important to note that this is not returning a value:

    fun divideByTwo(input: Double): Double {
    println(input) // I haven't returned anything yet...
    return input / 2.0
    }
    var value = 2.0
    println(value)
    value = divideByTwo(value)
    println(value)

    Homework: Game Tiebreaker Function

    Created By: Geoffrey Challen
    / Version: 2021.8.0

    Two players have completed a game. Write a method (or function) named whoWon to determine the winner!

    whoWon receives three parameters in the following order: the score of the first player as an Int, the score of the second player as an Int, and whether the first player played first as a Boolean.

    If either player scored more points than the other, they are the winner! However, if both players tie, then the player that played second is the winner.

    Return the result of the game as an Int. You should return 1 if Player 1 won and 2 if Player 2 won.

    If you have solved this problem previously without writing a method, you may reuse your old code! However, you may try to eliminate the winner variable that we used previously.

    More Practice

    Need more practice? Head over to the practice page.