Menu
Coddy logo textTech

Return Values

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 57 of 93.

Functions can do more than just perform actions - they can also send a value back to where they were called. To do this, you specify a return type after the parentheses and use the return keyword.

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

fun main() {
    val result = add(3, 5)
    println(result)
}
// Output: 8

The : Int after the parentheses declares that this function returns an integer. The return statement sends the value back and immediately exits the function. The caller can then store this value in a variable or use it directly.

Return values make functions much more versatile. Instead of just printing results, functions can calculate values that you use elsewhere in your program:

fun double(n: Int): Int {
    return n * 2
}

fun main() {
    println(double(7) + 1)
}
// Output: 15

If a function doesn't return anything meaningful, it has a return type of Unit. You can omit this type since Kotlin assumes it by default - that's why our earlier functions with just println() didn't need a return type.

challenge icon

Challenge

Medium

Write a function multiply that takes two integers and returns their product.

The function should multiply the two numbers together and return the result.

Parameters:

  • a (Int): The first number
  • b (Int): The second number

Returns: The product of a and b (Int)

Try it yourself

fun multiply(a: Int, b: Int): Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground