let
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
also
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...
}
takeIf
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!")
takeUnless
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!")
Help
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…