Higher-order Functions (part-II)
Explore how Kotlin simplifies handling collections with higher-order functions and lambda expressions. Understand how the compiler infers types and allows omitting parameter declarations for cleaner, more compact code. Gain confidence in writing and reading Kotlin’s expressive function calls.
We'll cover the following...
Lambda expressions
In the previous lesson, we started by trying to understand the following line of code:
var lengths = strings.map {it.length}
But what about the strange curly braces?
To introduce the curly braces, we need to ‘inline’ our transformation function.
Like any other variable, we can inline getLengthOfString by replacing that reference directly with its true value. In this case, this will be the transformation function itself. This is how it’s done:
In the snippet above, we replace the reference, getLengthOfString, with its actual value.
However, since the function is anonymous anyway and can no longer be referenced from the outside, we can write it in an even shorter way by using a lambda expression:
These look very similar to those of Java. ...