let的用法还有,如果在Kotlin中取不用的话?
我读了许多关于这些项目的kotlin文件。 但是我不太清楚。
Kotlin的用途是什么, 还有 , 如何 取得细节?
我需要每个项目的例子。 请不要发布Kotlin文档。 我需要一个实时的例子和这些项目的用例。
让
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
将接收器传递给作为参数传递的函数。 返回函数的结果。
val myVar = "hello!" myVar.let { println(it) } // Output "hello!"
你可以使用let
来进行null安全检查:
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 }
执行与接收器一起传递的函数作为参数并返回接收器 。
这就像让,但总是返回接收器 ,而不是函数的结果。
你可以使用它来做一个对象的东西。
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
如果函数(谓词)返回true,则返回接收者 ,否则返回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
和takeIf
,但谓词颠倒了。 如果为true,则返回null,否则返回接收者 。
println(myVar.takeUnless { it is Person } ?: "It's a person!")
帮帮我
- 您可以使用https://try.kotlinlang.org/轻松进行测试。 你可以在这里找到例子。
- 你可以在这里签出标准库的源代码。
let
在这里takeIf
,takeUnless
。
- 如何在Kotlin anko中使用TextInputLayout和TextInputEditText
- java.lang.ClassNotFoundException:com.intellij.junit5.JUnit5IdeaTestRunner在kotlin中使用spek
- 下载的文件列表为空
- NoSuchMethodError:java.lang.Long.hashCode
- Android Kotlin – 无法安排与警报管理器通知未来的日期
- 当处于调试器模式时,Android Studio 1.5与Kotlin Plugin异常。 如何解决它?
- Kotlin直接访问android.support.v4.app.Fragment中的Button对象引用
- TextColor正在改变到错误的一个
- 未解决的参考:数据绑定