Cody Engel

Software Engineer at ActiveCampaign

Let’s Learn How To Code Using Kotlin — Part 005 — Functions

We are now on part 6 of learning how to code and in this installment we are going to focus on learning about functions. For this lesson we are going modify our program created in part 004. However before we get started make sure you create a new package named part_005 and create a new Kotlin file named app. Awesome, let’s get started.

Ron Manke on Unsplash

I first want to talk about what a function is and what it might be called in other languages, basically I want to give some background on this topic before diving into the actual lesson. Functions help to promote code reuse, instead of having to write the same logic over and over again you simply package it into a function and it can be referenced in other areas of your application. In other languages these may be referred to as methods, but in Kotlin they are called functions.

If you are feeling a little nervous, don’t, we have been using functions since the beginning, it’s the thing that is called main that our applications have been wrapped in. For our lesson I want to take the work we did from our while loop and wrap that into a function so instead of printing only until we find a car with ford in the name. It’d be really nice if we could pass in a String and it will continue to loop until it finds that. So that’s what we are going to do.

Let’s Get Started

I’m going to provide a template that you can copy and paste into IntelliJ, actually please do because I want to also show you how autocomplete works.

fun main(args : Array<String>) {

    val cars = arrayOf(
            "Toyota Camry",
            "Toyota Corolla",
            "Honda Civic",
            "Nissan Altima",
            "Honda Accord",
            "Hyundai Elantra",
            "Nissan Sentra",
            "Ford Fusion",
            "Chevrolet Cruze",
            "Hyundai Sonata",
            "Ford Focus",
            "Mazda MX-5 Miata",
            "Fiat 124 Spider",
            "Subaru BRZ",
            "Toyota 86",
            "Nissan Z",
            "Dodge Challenger",
            "Ford Mustang",
            "Chevrolet Camaro",
            "Audi TT / TTS"
    )

    printUntilFound(cars, "ford")
}

Right now you should notice that printUntilFound is in red. Depending on if you are using Linux, Windows, or OS X the keyboard shortcuts for this action will differ so instead of giving you a set of keys to press I’ll just show you what you can click. As homework please do look up the keyboard shortcuts for IntelliJ at some point in time.

If the red lightbulb doesn’t appear, place your cursor over the name. You may have to click on different letters or over over different areas, but be patient and it will show up.

Once you select Create function 'printUntilFound' you’ll notice that it generates a method. Press enter on the keyboard until it generates code within the function (known as the function body). You should see something like this.

fun printUntilFound(cars: Array<String>, searchTerm: String) {
    throw UnsupportedOperationException("not implemented")
}

So what exactly are we looking at? The first line is the definition of our function. It contains the name, printUntilFound along with the parameters to pass in. The first parameter to pass in will be an Array of String objects, it’s named cars. The second parameter (which may default to s when auto generated) is named searchTerm which is a String. We will use searchTerm to essentially replace our hardcoded reference to ford.

The function body will currently throw an exception, which means the application will crash if we don’t handle that exception. This is one way to ensure that our code doesn’t call an empty function that doesn’t do anything. It can be useful in larger projects where you may think you are calling a function that does something but it was actually never implemented. Typically you’ll be deleting this right away and adding the logic required for the function.

One part about this function that may be confusing is we now have cars referenced in two spots of our application. So if it’s easier to understand, feel free to rename cars to something like carsArray.

Let’s Fill In The Body

So now it’s time to actually fill in the function body. Since you’ve already completed this for part 004 I would suggest trying to fill it in on your own and only look at the completed body if you get stuck.

Awesome, let’s go ahead and compare notes, here is what I came up with.

/**
 * Prints out a list of cars until it reaches a given search term.
 * It will print out the car that matches that search term and then
 * it will terminate.
 * @param cars a list of cars to print out
 * @param searchTerm the search term used to determine when to stop
 *        printing out cars.
 */
fun printUntilFound(cars: Array<String>, searchTerm: String) {
    var wasFound = false
    var index = 0;
    while (!wasFound) {
        val car = cars[index]
        println(car)
        wasFound = car.toLowerCase().contains(searchTerm)
        index++
    }
}

Okay so you probably didn’t include the function documentation, and that’s understandable because I never mentioned it. Documenting your code is very important, especially when you are working with other engineers. In two weeks or a month you can come back to this and know exactly what it should do. Another nice part about documentation is it reinforces that your function makes sense. There have been several times where I changed a function because I couldn’t easily describe it through documentation. I could go on for an entire article about documentation so I’ll digress for now.

So within this function body you should have replaced "ford" with searchTerm and that’s really all that should have changed. Now within the main function when you call this and pass in ford you should notice that it does exactly what it did previously. Go ahead and add printUntilFound(cars, “nissan”) to main and notice what happens. when you run the code. It should now only print out four items ending with Nissan Altima.

And that’s an overview of functions in Kotlin. There’s more to functions and we’ll likely go over them more in the future. One thing I did not talk about in this article are return values in functions. A return value is what you return to the call site (where the function was called) after the function has completed.

And that’s it for this article. As always if you have any questions or comments feel free to leave a response below. As an aside, you may have noticed there was no article about Kotlin last week. I strongly recommend that you follow me over on Twitter as I will always send out some announcement if I have to delay an article.

Cody Engel (@POTUS404) | Twitter

More by Cody Engel

More Related Stories