我阅读了很多关于这些项目的 Kotlin 文档。但我不能这么清楚。
Kotlin let、also、takeIf 和 takeUnless 有什么用处?
我需要每个项目的示例。请不要发布 Kotlin 文档。我需要这些项目的实时示例和用例。
最佳答案
让
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
获取 receiver 并将其传递给作为参数传递的函数。返回函数的结果。
val myVar = "hello!"
myVar.let { println(it) } // Output "hello!"
您可以使用 let
用于空安全检查:
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 }
执行以receiver为参数传递的函数,并返回receiver。
这就像 let 但总是返回 receiver,而不是函数的结果。
你可以用它在一个物体上做一些事情。
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
如果函数(谓词)返回true,则返回receiver,否则返回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
同 takeIf
,但谓词颠倒。如果为 true,则返回 null,否则返回 receiver。
println(myVar.takeUnless { it is Person } ?: "It's a person!")
帮助
- 您可以使用https://try.kotlinlang.org/便于测试。您可以找到示例 here .
- 您可以查看标准库的源代码 here .
let
,also
,takeIf
和takeUnless
here .
关于android - kotlin 之间的区别还有,apply,let,use,takeIf 和 takeUnless 在 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582732/