Lambda Functions

suggest change

Lambda 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 })

Feedback about page:

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



Table Of Contents