Kotlin 操做符:run、with、let、also、apply 的差别与选择

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 操做符,当使用这个函数时,咱们所须要问题的有三点:函数

  • this 的含义(接收器)
  • it 的含义(参数)
  • result 最终获得的什么

由于咱们使用的是 let,因此对应是:测试

  • 『 this 』为『 this @ MyClass 』, this 是 MyClass 的实例,由于 test() 是 MyClass 的一个方法。而若是 test() 是一个空函数(Free function —— 不附加到任何类),将会出现一个编译错误。
  • 『 it 』为原字符串自己『 Boss 』
  • 『 result 』是数字 69,咱们已经从区间返回赋值

咱们用表格更直观的做显示:ui

操做符 接收者(this) 传参(it) 返回值(result)
let this@Myclass String( "Boss" ) Int( 69 )

依此类推:咱们能够这段代码为其他的功能作相似的事情。this

如下是测试操做符通用的代码,你可使用 let、run、apply、also 中任何的操做符替换 xxxspa

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

而关于何时咱们应该用到什么操做符,能够参考这个图:

Function_selections
Function_selections

参考文章:

  1. Mastering Kotlin standard functions: run, with, let, also and apply
  2. The difference between Kotlin’s functions: ‘let’, ‘apply’, ‘with’, ‘run’ and ‘also’
相关文章
相关标签/搜索