๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Function Types

A function type describes the parameters and the return of a function value. A value with that type can sit in a variable just like a number or a string.

A typed function value

The variable add holds a lambda with the type (Int, Int) -> Int. It can be called by name or with invoke.

fun main() {
    val add: (Int, Int) -> Int = { a, b -> a + b }
    println(add(4, 5))
    println(add.invoke(4, 5))
}

A string in, a string out

This function type takes one String and returns one String. The lambda builds a greeting from its parameter.

fun main() {
    val greet: (String) -> String = { name -> "Hello, " + name }
    println(greet("Mia"))
}

A function type with Unit

The type () -> Unit takes no parameters and returns nothing. Calling the value runs its printing code.

fun main() {
    val cheer: () -> Unit = { println("Hooray") }
    cheer()
    cheer()
}

A shorter name with typealias

The typealias ScoreCheck stands for the type (Int) -> Boolean. The variable uses the short name as its type.

typealias ScoreCheck = (Int) -> Boolean

fun main() {
    val passed: ScoreCheck = { score -> score >= 60 }
    println(passed(75))
    println(passed(40))
}

A lambda with the wrong type

The variable declares the type (Int) -> Int, but the lambda takes a String. The compiler refuses the program and names both types.

fun main() {
    val scale: (Int) -> Int = { text: String -> text.length }
    println(scale(3))
}

Example

fun main() {
    val double: (Int) -> Int = { x -> x * 2 }
    val label: (Int) -> String = { x -> "Score " + x }
    println(label(double(21)))
}

Key points

  • Write a function type with the parameter types in parentheses, an arrow, and the return type.
  • The type (Int, Int) -> Int takes two Int values and returns an Int.
  • Call a stored function by its name, just like a plain function.
  • The invoke call runs a stored function as well.
  • A function type with no return value ends in Unit.
  • A typealias gives a function type a shorter name.

In this example, double turns 21 into 42. The label value then turns 42 into the text Score 42. Each stored function runs by its variable name.

Note

The compiler checks a stored lambda against its declared function type.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does the type (String) -> Int describe?