Basic Lambdas

suggest change

Syntax

Remarks

Input types can be left out when they can be inferred from the context. For example, say you have a function on a class that takes a function:

data class User(val firstName: String, val lastName: String) {
    fun username(userNameGenerator: (String, String) -> String) =
        userNameGenerator(firstName, lastName)
}

You can call this function with a lambda. Because the parameter types are already specified, you do not redeclare them in the lambda:

val user = User("foo", "bar")
println(user.username { firstName, lastName ->
    "${firstName.uppercase()}_${lastName.uppercase()}"
}) // prints FOO_BAR

This also applies when you assign a lambda to a variable:

// valid:
val addition: (Int, Int) -> Int = { a, b -> a + b }
// valid:
val addition2 = { a: Int, b: Int -> a + b }
// error (type inference failure):
// val addition3 = { a, b -> a + b }

When the lambda takes one parameter, and the type can be inferred from the context, you can refer to the parameter by it.

listOf(1, 2, 3).map { it * 2 } // [2, 4, 6]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents