Lambda Functions
suggest changeLambda functions are anonymous functions which are usually created during a function call to act as a function parameter. They are declared by surrounding expressions with braces. If arguments are needed, they are put before an arrow ->.
{ name: String ->
"Your name is $name" //This is returned
}
The last statement inside a lambda function is automatically the return value.
The types are optional if you put the lambda where the compiler can infer them.
Multiple arguments:
{ argumentOne: String, argumentTwo: String ->
"$argumentOne - $argumentTwo"
}
If the lambda function only needs one argument, then the argument list can be omitted and the single argument is referred to using it instead.
{ "Your name is $it" }
If the only argument to a function is a lambda, then parentheses can be omitted from the function call.
// These are identical
listOf(1, 2, 3, 4).map { it + 2 }
listOf(1, 2, 3, 4).map({ it + 2 })
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents