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.
As the name says, also expressions does some additional processing on the object it was invoked. Unlike let, it returns the original object instead of any new return data. Hence the return data has always the same type. Like let , also uses it too.
There're two differences: apply accepts an instance as the receiver while with requires an instance to be passed as an argument. In both cases the instance will become this within a block. apply returns the receiver and with returns a result of the last expression within its block.
In short, takeIf() can be called on any non-null object (the subject) and takes a predicate as an argument. If the predicate is satisfied (is true), the subject is returned, otherwise null is returned. Meaning we can replace this: return if(x. isValid()) x else null.
let is often used for executing a code block only with non-null values. To perform actions on a non-null object, use the safe call operator ?. on it and call let with the actions in its lambda. Another case for using let is introducing local variables with a limited scope for improving code readability.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With