I read many Kotlin documents about these items. But I can't understand so clearly.
What is the use of Kotlin let, also, takeIf and takeUnless in detail?
I need an example of each item. Please don't post the Kotlin documentation. I need a real-time example and use cases of these items.
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
Take the receiver and pass it to a function passed as a parameter. Return the result of the function.
val myVar = "hello!"
myVar.let { println(it) } // Output "hello!"
You can use let
for null safety check:
val myVar = if (Random().nextBoolean()) "hello!" else null
myVar?.let { println(it) } // Output "hello!" only if myVar is not null
public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }
Execute the function passed with the receiver as parameter and return the receiver.
It's like let but always return the receiver, not the result of the function.
You can use it for doing something on an object.
val person = Person().also {
println("Person ${it.name} initialized!")
// Do what you want here...
}
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
Return the receiver if the function (predicate) return true, else return null.
println(myVar.takeIf { it is Person } ?: "Not a person!")
public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? = if (!predicate(this)) this else null
Same as takeIf
, but with predicate reversed. If true, return null, else return the receiver.
println(myVar.takeUnless { it is Person } ?: "It's a person!")
let
, also
, takeIf
and takeUnless
here.