Start learning free

LESSON 34 OF 348 · FUNCTIONS I

Why Use Functions in Kotlin: Reuse Code with fun

Lesson Read the full explanation

Now that we've learned about functions, let's see why they are so important in our prgrammers' life:

Consider this: A student named Andy made a mistake and so his teacher told him to write this text 3 times on the whiteboard:

This is Andy
Andy made a mistake
Andy suffers the consequences

We would put this in a simple program like this:

println("This is Andy")
println("Andy made a mistake")
println("Andy suffers the consequences")

println("This is Andy")
println("Andy made a mistake")
println("Andy suffers the consequences")

println("This is Andy")
println("Andy made a mistake")
println("Andy suffers the consequences")

That's manageable. But what if the text consisted of more than 3 lines? And what if the teacher asked Andy to print it for 10 times or 100 times?

You can imagine that our code would get super long while executing 3 different instructions overall.


The story with functions:

This is where functions shine. We can write a function that prints the desired text and then just call the function for as many times as the teacher asks to:

fun printMessage() {
	println("This is Andy")
	println("Andy made a mistake")
	println("Andy suffers the consequences")
}

printMessage()
printMessage()
printMessage()

Changing the story:

Need to print the text 3 more times? We call the function 3 more times instead of adding 9 lines to our program.

Need to change the student's name to Mike? We only change it inside the function instead of changing it in the whole program.

fun printMessage() {
	println("This is Mike")
	println("Mike made a mistake")
	println("Mike suffers the consequences")
}

printMessage()
printMessage()
printMessage()
printMessage()
printMessage()

Note:

If you still don't like this code, especially the fact that we have 5 duplicate lines of code: printMessage(), you are correct! We will learn how we can make this even better with loops!


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · FUNCTIONS I

    Why Functions in Kotlin, explained

    The problem: repeated code

    Imagine a student who has to write the same three lines on a whiteboard three times. The direct way to do this in a program is to write each println out three times, nine statements in total:

    println("This is Andy")
    println("Andy made a mistake")
    println("Andy suffers the consequences")
    
    println("This is Andy")
    println("Andy made a mistake")
    println("Andy suffers the consequences")
    
    println("This is Andy")
    println("Andy made a mistake")
    println("Andy suffers the consequences")
    

    That is manageable for three copies. Now picture 100 copies of ten lines, or a request to change the name in every one of them. The program grows with each repetition, and every change has to be made in every copy. A copy you forget leaves the program inconsistent.

    The fix: write it once, call it many times

    A function packages the lines under a name. You write the lines once, in the body, and run them with a call each time you need them:

    fun printMessage() {
        println("This is Andy")
        println("Andy made a mistake")
        println("Andy suffers the consequences")
    }
    
    fun main() {
        printMessage()
        printMessage()
        printMessage()
    }
    

    Both programs print the same nine lines, but the function version is shorter and it scales. Three more repetitions cost three more lines of the form printMessage(), not nine copied println statements. If the student's name changes to Mike, you edit the three lines inside the function, and every call picks up the change.

    That is the main reason functions exist: they remove duplication, and so there is one place to read, test and fix each piece of logic. A second reason is that a name documents the intent. A reader who sees printMessage() knows what the line does without reading its body.

    Kotlin details

    • Defining isn't running. The definition only stores the body. Nothing prints until a call such as printMessage() executes it.
    • Each call runs the full body. Three calls give three complete sets of output, always starting at the first line of the body.
    • No return type is written. A function with a block body and no declared return type returns Unit, Kotlin's "nothing useful". You don't write it for functions that only print.
    • Calls go inside functions. The snippets above put the calls in main. In this lesson they go in mainFunction.

    The lesson's exercise, step by step

    The starter code has a comment where the function goes, and a mainFunction that already prints Sorry, I didn't hear you between two comments. The task is to write one function and call it twice, with the extra line coming between the two calls.

    1. Define introduceYourself under the first comment, with fun, empty parentheses and braces. It takes no input and returns nothing, so no return type is needed.
    2. Print the first line inside it, My name is Andy.
    3. Print the second line, I code in Python, on the next line of the body. Both introduction lines now live in one place.
    4. Call introduceYourself() in mainFunction under the first comment. This is the first introduction.
    5. Call it again under the last comment, after the Sorry, I didn't hear you line. The two lines print a second time without being typed again.
    // Function goes here:
    fun introduceYourself() {
        println("My name is Andy")
        println("I code in Python")
    }
    
    
    fun mainFunction() {
        // Introduce yourself the first time:
        introduceYourself()
    
        println("Sorry, I didn't hear you")
    
        // Introduce yourself again:
        introduceYourself()
    
    }
    

    Run through main, this code prints:

    My name is Andy
    I code in Python
    Sorry, I didn't hear you
    My name is Andy
    I code in Python
    

    The text of the second line is part of what the lesson checks, so it must match exactly, even though the program is written in Kotlin.

    Common mistakes

    • Forgetting the second call. The output then ends after Sorry, I didn't hear you.
    • Calling before the apology line. Both calls must be placed on either side of that println, so the output order is introduction, apology, introduction.
    • Leaving out the parentheses. introduceYourself without () is not a call, and the compiler rejects it.
    • Copying the two println lines into mainFunction instead. The output might match, but the point of the lesson, a single place for the introduction, is lost.

    Key takeaways

    • A function lets you write a block of code once and run it as many times as you need.
    • Changing the function body changes every call.
    • Name a function after what it does, so that calls read like instructions.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free