๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Returning Values

A returning function is a function that gives a value back to its caller. The word return sends that value back from the function body.

A value given back with return

add adds its two numbers and sends the sum back with return. The call stands where a value belongs.

fun add(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    val total = add(3, 4)
    println(total)
}

Storing and using the given back value

The value from square is stored before the prints run. The stored value can print alone and can join a new sum.

fun square(side: Int): Int {
    return side * side
}

fun main() {
    val area = square(5)
    println(area)
    println(area + 1)
}

The single-expression short form

One = sign can replace the braces and the return word. double still gives back twice its input each time.

fun double(x: Int): Int = x * 2

fun main() {
    println(double(6))
    println(double(9))
}

A typed function must give a value back

This function marks its result as Int but its body only prints. The compiler stops the program with this error.

fun answer(): Int {
    println(42)
}

fun main() {
    println(answer())
}

Example

fun triple(x: Int): Int {
    return x * 3
}

fun main() {
    val result = triple(4)
    println(result)
    println(result + triple(1))
}

Key points

  • return: the keyword that sends a value back from a function.
  • The type after the parentheses names the kind of value the function gives back.
  • Use return to send a value back, then store that value with val.
  • Single-expression function: a short function written as one = sign and one expression.

In this example, triple gives back three times its input. The first call stores 12 in result and the first print shows 12. The second call gives back 3. The last print adds 12 and 3 and shows 15.

Note

The value after return must match the type named after the parentheses.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

The function fun double(x: Int): Int = x * 2 runs with double(7). What value comes back?