Basic Lambdas
suggest changeSyntax
- Explicit parameters:
- { parameterName: ParameterType, otherParameterName: OtherParameterType -> anExpression() }
- Inferred parameters:
- val addition: (Int, Int) -> Int = { a, b -> a + b }
- Single parameter
itshorthand - val square: (Int) -> Int = { it*it }
- Signature:
- () -> ResultType
- (InputType) -> ResultType
- (InputType1, InputType2) -> ResultType
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]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents