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 ${
first