0
0
KotlinHow-ToBeginner · 3 min read

How to Return Value from Function in Kotlin: Simple Guide

In Kotlin, you return a value from a function using the return keyword followed by the value. The function must declare the return type after the function name using a colon, like fun example(): Int.
📐

Syntax

To return a value from a function in Kotlin, you declare the return type after the function name using a colon. Inside the function body, use the return keyword followed by the value you want to send back.

  • fun: keyword to declare a function
  • functionName: name of the function
  • (): ReturnType: parentheses for parameters and colon with return type
  • return value: sends the value back to the caller
kotlin
fun functionName(): ReturnType {
    return value
}
💻

Example

This example shows a function that returns the sum of two numbers. It declares the return type Int and uses return to send the result back.

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

fun main() {
    val result = add(5, 3)
    println("Sum is: $result")
}
Output
Sum is: 8
⚠️

Common Pitfalls

One common mistake is forgetting to specify the return type when the function returns a value. Another is missing the return keyword inside the function body. Also, if the function has a single expression, you can use the expression body syntax without return.

kotlin
/* Wrong: Missing return type */
fun multiply(a: Int, b: Int) {
    return a * b // Error: function must declare return type
}

/* Correct: Specify return type */
fun multiply(a: Int, b: Int): Int {
    return a * b
}

/* Shorter syntax for single expression */
fun multiplyShort(a: Int, b: Int): Int = a * b
📊

Quick Reference

Remember these tips when returning values in Kotlin functions:

  • Always declare the return type if your function returns a value.
  • Use return keyword to send the value back.
  • For single-expression functions, use the concise syntax without braces.
  • Functions without return type or with Unit return nothing.

Key Takeaways

Use the return keyword followed by the value to return from a Kotlin function.
Declare the return type after the function name with a colon.
Single-expression functions can omit braces and the return keyword.
Functions without a return type or with Unit return no meaningful value.
Always match the declared return type with the returned value type.