TExcelTAD
Home › Kotlin › Kotlin Functions

Kotlin Functions

A function is a named, reusable block of code. You've already used many — println, listOf, uppercase. Now you'll write your own. Functions let you give a name to an idea, avoid repeating code and test pieces of a program on their own.

Declaring and calling a function

kotlin · try it yourself
fun greet() {
    println("Hello there!")
}

fun main() {
    greet()
    greet()
}
Hello there!
Hello there!

Parameters

Parameters are inputs. Each one is written name: Type, and the type is always required — Kotlin doesn't infer parameter types.

kotlin · try it yourself
fun greet(name: String, times: Int) {
    for (i in 1..times) {
        println("Hello, $name!")
    }
}

fun main() {
    greet("Mia", 2)
    greet("Noah", 1)
}
Hello, Mia!
Hello, Mia!
Hello, Noah!

Parameters are read-only inside the function, like vals.

Return values

Declare the return type after the parameter list and use return to send a value back:

kotlin · try it yourself
fun areaOfRectangle(width: Double, height: Double): Double {
    return width * height
}

fun main() {
    val area = areaOfRectangle(3.0, 4.5)
    println("Area: $area")
    println("Two rooms: ${areaOfRectangle(2.0, 2.0) + areaOfRectangle(3.0, 3.0)}")
}
Area: 13.5
Two rooms: 13.0

A function without a declared return type returns Unit — Kotlin's "nothing useful" type, similar to void.

Single-expression functions

If the body is a single expression, drop the braces and return and use =. The return type can then be inferred:

kotlin · try it yourself
fun square(n: Int) = n * n
fun isEven(n: Int) = n % 2 == 0
fun label(n: Int): String = if (isEven(n)) "even" else "odd"

fun main() {
    println(square(7))
    println(isEven(10))
    println(label(7))
}
49
true
odd
Style Example
block body fun f(x: Int): Int { return x + 1 }
expression body fun f(x: Int) = x + 1
no return value fun log(msg: String) { println(msg) }

Calling functions from functions

Small functions compose into bigger ones. Each function should do one thing:

kotlin · try it yourself
fun celsiusToFahrenheit(c: Double) = c * 9 / 5 + 32

fun describe(c: Double): String {
    val f = celsiusToFahrenheit(c)
    return "$c °C = $f °F"
}

fun main() {
    println(describe(0.0))
    println(describe(37.0))
    println(describe(100.0))
}
0.0 °C = 32.0 °F
37.0 °C = 98.6 °F
100.0 °C = 212.0 °F

Recursion

A function may call itself. Every recursive function needs a base case that stops the recursion:

kotlin · try it yourself
fun factorial(n: Int): Long = if (n <= 1) 1 else n * factorial(n - 1)

fun main() {
    for (n in listOf(1, 5, 10, 20)) println("$n! = ${factorial(n)}")
}
1! = 1
5! = 120
10! = 3628800
20! = 2432902008176640000

Tip: Mark a function whose recursive call is the very last operation with tailrec and the compiler turns it into a loop — no risk of a stack overflow.

Variable number of arguments

vararg lets a function accept any number of values; inside, the parameter behaves like an array:

kotlin
fun total(vararg prices: Double) = prices.sum()

total(1.5, 2.0, 3.25)   // 6.75

Local functions

Functions can be declared inside other functions. They're visible only there and can use the outer function's variables — handy for small helpers.

Test yourself

What is the return type of fun f(x: Int) = x > 0?

  1. Int
  2. Boolean
  3. Unit
  4. Any

Which return type does a function without a declared type and with a block body have?

  1. Any
  2. Nothing
  3. Unit
  4. Void

Can you omit parameter types in a Kotlin function declaration?

  1. Yes, they are inferred
  2. No, parameter types are always required
  3. Only for Int
  4. Only in single-expression functions