Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

android - difference between kotlin also, apply, let, use, takeIf and takeUnless in Kotlin

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...