gpt4 book ai didi

android - kotlin 之间的区别还有,apply,let,use,takeIf 和 takeUnless 在 Kotlin

转载 作者:IT老高 更新时间:2023-10-28 13:30:04 26 4
gpt4 key购买 nike

我阅读了很多关于这些项目的 Kotlin 文档。但我不能这么清楚。

Kotlin letalsotakeIftakeUnless 有什么用处?

我需要每个项目的示例。请不要发布 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!")

帮助

关于android - kotlin 之间的区别还有,apply,let,use,takeIf 和 takeUnless 在 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com