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’
相關文章
相關標籤/搜索