Careeroza
Function Types
Writing Function Types
Every lambda has a function type that lists the parameter types and the return type.
| Function type | Meaning | Example value |
|---|---|---|
() -> Unit | no input, no result | { println("hi") } |
(Int) -> Int | Int in, Int out | { it * 2 } |
(String, Int) -> Boolean | two inputs, Boolean out | { s, n -> s.length > n } |
((Int) -> Unit)? | nullable function | null |
String.() -> Unit | function 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!