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!") 

帮帮我