In Kotlin, every type has a let()
and apply()
extension function. These are two simple but helpful tools to make your code more fluent and expressive.
let()
simply accepts a lambda that maps the invoked object T
to another object R
. It is similar to how RxJava offers the to()
operator, but it applies to any type T
and not just Observables/Flowables. For example, we can call let()
on a string that has been lowercased and then immediately do any arbitrary transformation on it, such as concatenating its reversed()
string to it. Take a look at this operation:
fun main(args: Array<String>) { val str = "GAMMA" val lowerCaseWithReversed = str.toLowerCase().let { it + " " + it.reversed() } println(lowerCaseWithReversed) }
The output is as follows:
gamma ammag
The let()
comes in handy when you do not want to save a value to a variable just so you can refer to it multiple times. In the preceding code, we did not have to save the result of...