CodeBlanks Logo Icon CodeBlanks

Return values

Learn to return a value from a function with return.

Return values: return and return type

A function can return a value. The return type is written after the parameter parentheses as : Type; the body uses return value to exit. Functions that return no value have return type Unit (or it is omitted).

fun add(a: Int, b: Int): Int {
    return a + b
}
val sum = add(3, 4)  // 7

return exits the function and hands the value to the caller. In Unit-returning functions return is either value-less or not used.

Unit and implicit return

If a function returns no value, its return type is Unit. Writing Unit is optional; fun greet(name: String) { println(name) } actually means fun greet(name: String): Unit { ... }.

fun greet(name: String): Unit {
    println("Hello $name")
}
// Omitting Unit means the same

println itself returns Unit. So a line that calls println has the value Unit; assigning it to another variable is meaningless.

Practice Define square and call it

Define a fun square(x: Int): Int whose body is return x * x. From main print the result with println(square(5)).

Starter code

Main.kt
fun main() {
    // Print the square(5) call with println
}

// Define square: Int parameter, returns Int, returns x * x

Sample solution

Main.kt
fun main() {
    println(square(5))
}

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

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does fun square(x: Int): Int { return x * x } return?

  • String
  • Unit
  • Int Correct answer
  • Boolean

Explanation: The return type is declared Int; x * x is an Int.

2 Match expression to role

Term Meaning
return x + y Returns the value
: Int Return type Int
: Unit Returns no value
return (alone) Exits the block

3 Fill in the blank: return the value

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

Explanation: return a + b hands the value to the caller.

All lessons in Beginner