Kotlin for C# Developers

5.2. Defining lambdas

Remember that function parameters are passed as name: Type in Kotlin, for example:

fun multiplyBy2(value: Int) = value * 2

Kotlin also supports lambdas, which are passed to functions using the following syntax:

fun doLongRunningTask(onDone: () -> Unit) {
    figureOutMeaningOfLife()
    onDone()
}

So here the name of the lambda parameter is onDone and its type is () -> Unit:

Here’s an example with a lambda that takes a parameter and returns something:

fun logAsString(int: Int, convertToString: (Int) -> String) {
    val string = convertToString(int)
    println(string)
}

Next: Calling lambdas