首先 also 英语是而且的意思 let是允许
also的源码是这样的
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
retrun this操作对象后返回对象。
package com.yzdzy.kotlin.temp
fun main() {
val res= "Also".also {
println(it.length)
it.replace("Also","狗蛋")
}
println(res)
}
输出
4
Also
这点要是切换到let。。。就会返回最后一行的结果
let 源码
/**
* Calls the specified function [block] with `this` value as its argument and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#let).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
代码示例
package com.yzdzy.kotlin.temp
fun main() {
val res= "let".let {
println(it.length)
it.replace("let","狗蛋")
}
println(res)
}
输出
3
狗蛋