Introduction to Function Returns in Kotlin

Welcome, learners! Today, we're diving into function return values in Kotlin programming. Function return values, often simply referred to as "returns," are results given back by a function after performing its assigned task. This concept is signified in Kotlin with the keyword return.

Here's a simple example of a function greet() that returns a String:

fun greet(): String {
    // This function will return the following string
    return "Hello, there!"
}
Using Function Returns: Working examples

Now, let's get more practical. Suppose we want our function to perform a calculation—an addition operation in a calculator program, for instance. Here's how we can write a function that adds two numbers and returns the sum:

fun addNumbers(num1: Int, num2: Int): Int {
    // This function adds num1 and num2 and returns the sum.
    return num1 + num2
}

Let's see this function in action within Kotlin's main function:

fun main() {
    // Call addNumbers with 5 and 7 as parameters, print the returned value
    println(addNumbers(5, 7)) // Output: 12
}
Exploring Data Types in Returns

Returns are not always simple numbers. A function can return any type of data from the range Kotlin supports, including Int, String, Double, Boolean, Char, and Long. Let's explore this further using the calculation of a circle's area as an example, which is πr².

fun circleArea(radius: Double): Double {
    // This function calculates the circle's area and returns it.
    return 3.14 * radius * radius
}
Creating Multi-line Functions

Functions don't have to be limited to one line. Kotlin functions can span multiple lines and still return a value. Suppose, for instance, that we want to determine whether a student has passed or failed based on their score:

fun passOrFail(score: Int): String {
    var result = "Fail"
    
    if (score > 75) {
        result = "Pass"
    }
    
    return result
}
Multiple Returns

It's possible that a function has multiple return statements. When a return statement is reached, the function stops running, and all subsequent code within it is ignored. This ensures that the function exits as soon as it fulfills a condition that leads to a return:

fun passOrFail(score: Int): String {
    if (score > 75) {
        return "Pass" // If this condition is met, the function immediately exits with "Pass"
    }
    
    return "Fail" // If the condition above is not met, the function returns "Fail"
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal