以下例子我們將前置代碼的回傳值稱為 T,花括號部分稱為 block,以彈出桌面程式選擇框為例:
var intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
intent.setClassName("android", "com.android.internal.app.ResolverActivity")
startActivity(intent)
總結
- let 與 also 將 T 作為 it 傳入 block,區別在于回傳結果分別為 block 最后一行結果與 T本身
- run 與 apply 將 T 作為 this 傳入 block,區別在于回傳結果分別為 block 最后一行結果與 T本身
- with 也是將 T 作為 this 傳入 block 并回傳 block 最后一行結果,區別在于寫法是 with(T)

1、let – block: (T) -> R
- Calls the specified function [block] with ‘this’ value as its argument and returns its result.
- 百度翻譯:用 this 值作為 引數 呼叫指定的函式 [block],并回傳結果,
- 個人理解:將 T 作為 it 傳入 block 并回傳結果(T 為 intent,block 為 let 后的 {} 及內容)
var intent = Intent(Intent.ACTION_MAIN)
intent.let {//it:Intent
it.addCategory(Intent.CATEGORY_HOME)
it.setClassName("android", "com.android.internal.app.ResolverActivity")
startActivity(it)//這里無回傳值,所以整體let也是無回傳值的
}.let{//it:Unit
}
2、also – block: (T) -> Unit
- Calls the specified function [block] with ‘this’ value as its argument and returns
thisvalue. - 百度翻譯:以 this 值作為 引數 呼叫指定的函式 [block],并回傳 this 值,
- 個人理解:將 T 作為 it 傳入 block 并回傳 T
intent.also {//it:Intent
it.addCategory(Intent.CATEGORY_HOME)
it.setClassName("android", "com.android.internal.app.ResolverActivity")
startActivity(it)
}.let{//it:Intent
}
3、run – block: T.() -> R
- Calls the specified function [block] with
thisvalue as its receiver and returns its result. - 百度翻譯:以 this 值作為其 接收器 呼叫指定的函式 [block],并回傳其結果,
- 個人理解:將 T 作為 this 傳入 block 并回傳 block 最后一行結果,this 可以省略
intent.run {//this:Intent
addCategory(Intent.CATEGORY_HOME)
setClassName("android", "com.android.internal.app.ResolverActivity")
startActivity(this)
}.let{//this:Unit
}
4、apply – block: T.() -> Unit
- Calls the specified function [block] with
thisvalue as its receiver and returnsthisvalue. - 百度翻譯:以 this 值作為其 接收器 呼叫指定的函式 [block],并回傳 this 值,
- 個人理解:將 T 作為 this 傳入 block 并回傳 T
intent.apply {//this:Intent
addCategory(Intent.CATEGORY_HOME)
setClassName("android", "com.android.internal.app.ResolverActivity")
startActivity(this)
}.let{//this:Intent
}
//可以這么寫,因為apply回傳值還是intent,執行順序也是先apply再startActivity
startActivity(Intent(Intent.ACTION_MAIN).apply {
addCategory(Intent.CATEGORY_HOME)
setClassName("android", "com.android.internal.app.ResolverActivity")
activity?.finish()
})
5、with – receiver: T, block: T.() -> R
- Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
- 百度翻譯:以給定的 [receiver] 作為其 接收器 呼叫指定的函式 [block],并回傳其結果,
- 個人理解:將接收部分(T)作為 this 傳入 block 并回傳 block 最后一行結果
with(Intent(Intent.ACTION_MAIN)){//this:Intent
addCategory(Intent.CATEGORY_HOME)
setClassName("android", "com.android.internal.app.ResolverActivity")
startActivity(this)
}.let{//this:Unit
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/267357.html
標籤:其他
上一篇:iOS 代理和block
