Kotlin 操做符:run、with、let、also、apply 的差别与选择 android
Kotlin 的一些操做符很是类似,咱们有时会不肯定使用哪一种功能。在这里我将介绍一个简单的方法来清楚地区分他们的差别,最后以及如何选择使用。bash
首先咱们如下这个代码:app
class MyClass {
fun test() {
val str: String = "Boss"
val result = str.let {
print(this) // 接收者
print(it) // 参数
69 //区间返回值
}
print(result)
}
}复制代码
在上面个例子中,咱们使用了 let 操做符,当使用这个函数时,咱们所须要问题的有三点:函数
由于咱们使用的是 let,因此对应是:测试
咱们用表格更直观的做显示:ui
操做符 | 接收者(this) | 传参(it) | 返回值(result) |
---|---|---|---|
let | this@Myclass | String( "Boss" ) | Int( 69 ) |
依此类推:咱们能够这段代码为其他的功能作相似的事情。this
如下是测试操做符通用的代码,你可使用 let、run、apply、also 中任何的操做符替换 xxx。spa
class MyClass {
fun test() {
val str: String = "Boss"
val result = str.xxx {
print(this) // 接收者
print(it) // 参数
69 //区间返回值
}
print(result)
}
}复制代码
返回值为:code
操做符 | 接收者(this) | 传参(it) | 赋值(result) |
---|---|---|---|
T.let() | this@Myclass | String( "Boss" ) | Int( 69 ) |
T.run() | String( "Boss" ) | 编译错误 | Int( 69 ) |
T.apply() | String( "Boss" ) | 编译错误 | String( "Boss" ) |
T.also() | this@Myclass | String( "Boss" ) | String( "Boss" ) |
with 与 also 操做符在使用上有一些细微的差别,例如:cdn
class MyClass {
fun test() {
val str: String = "Boss"
val result = with(str) {
print(this) // 接收者
// print(it) // 参数
69 //区间返回值
}
print(result)
}
}复制代码
class MyClass {
fun test() {
val str: String = "Boss"
val result = run {
print(this) // 接收者
// print(it) // 参数
69 //区间返回值
}
print(result)
}
}复制代码
操做符 | 接收者(this) | 传参(it) | 返回值(result) |
---|---|---|---|
run() | this@Myclass | 编译错误 | Int( 69 ) |
with(T) | String("Boss") | 编译错误 | Int( 69 ) |
合二为一:
操做符 | 接收者(this) | 传参(it) | 返回值(result) |
---|---|---|---|
T.let() | this@Myclass | String( "Boss" ) | Int( 69 ) |
T.run() | String( "Boss" ) | 编译错误 | Int( 69 ) |
run() | this@Myclass | 编译错误 | Int( 69 ) |
with(T) | String( "Boss" ) | 编译错误 | Int( 69 ) |
T.apply() | String( "Boss" ) | 编译错误 | String( "Boss" ) |
T.also() | this@Myclass | String( "Boss" ) | String( "Boss" ) |
而关于何时咱们应该用到什么操做符,能够参考这个图:
参考文章: