Function Types

Writing Function Types

Every lambda has a function type that lists the parameter types and the return type.

Function typeMeaningExample value
() -> Unitno input, no result{ println("hi") }
(Int) -> IntInt in, Int out{ it * 2 }
(String, Int) -> Booleantwo inputs, Boolean out{ s, n -> s.length > n }
((Int) -> Unit)?nullable functionnull
String.() -> Unitfunction with receiver{ println(uppercase()) }

Function Types in Practice

Example

fun main() {
    val isLong: (String, Int) -> Boolean = { s, n -> s.length > n }
    var onDone: ((String) -> Unit)? = null

    println(isLong("Kotlin", 4))
    onDone?.invoke("not called")         // safe call on a nullable function
    onDone = { msg -> println("Done: $msg") }
    onDone?.invoke("upload")

    val shout: String.() -> String = { uppercase() + "!" }   // 'this' is the String
    println("hello".shout())
}

Output

true
Done: upload
HELLO!