Kotlin 的 Scope Functions
Kotlin 的这几个语法糖的用法都是比较相似的:
let
The context object is available as an argument (it). The return value is the lambda result.
val str: String? = "Hello"
//processNonNullString(str) // compilation error: str can be null
val length = str?.let {
println("let() called on $it")// 'it' refers to 'str: String = "Hello"'
processNonNullString(it) // OK: 'it' is not null inside '?.let { }'
it.length
}
with
A non-extension function:
the context object is passed as an argument,
but inside the lambda, it’s available as a receiver (this). The return value is the lambda result.
val numbers = mutableListOf("one", "two", "three")
val firstAndLast = with(numbers) {
"The first element is ${
<

本文深入探讨了Kotlin中的Scope Functions,包括let、with、run、apply和also的用法和区别。重点介绍了如何根据需求选择合适的Scope Function,并解释了receiver的概念,它代表函数所属的类。通过实例展示了如何使用这些函数以简化代码并提高可读性。
最低0.47元/天 解锁文章
810

被折叠的 条评论
为什么被折叠?



