Files
Obsidian-Main/03. Programming/Kotlin/run, let, with, also 和 apply.md
Awin Huang abd315c585 vault backup: 2022-09-30 21:23:03
Affected files:
03. Programming/Kotlin/run, let, with, also 和 apply.md
2022-09-30 21:23:03 +08:00

65 lines
2.4 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
run, let, with, also 和 apply 這幾個都是可以搭配object 使用的函數,它們之間的差異不大,主要是讓程式看起來更符合語意。
以下解釋各個的差別。
## run
run後面的區塊會**回傳「最後一行」**,所以可以進行「串接」。如下:
```kotlin
run {
val telephone = Telephone()
telephone.whoCallMe = "English"
telephone // <-- telephone 被帶到下一個 Chain
}.callMe("Softest part of heart") // <-- 這裡可以執行 `Telephone` Class 的方法
```
## object.run
object.run跟[[run, let, with, also 和 apply#run]]是一樣的只是object.run是讓object呼叫的而且lambda scope中的物件會變成this如下
```kotlin
val anObject = MyObject()
anObject.run {
this.doSomething() // this就是anObject
}
```
## with
`with(T)` 之中的傳入值可以以 `this` (稱作 identifier) 在 scope 中取用,不用打出 `this`也沒關係。雖然, `with` 也會**將最後一行回傳**。但是因為with沒有先判斷物件是否為null所以scope中還是要用?來判斷是否null如下
```kotlin
val anObject = makeMyObject() // anObject有可能是null
with(anObject) {
this?.doSomething() // this就是anObjectthis可能是null
}
```
## let
let的scope裡物件是it一樣會**回傳最後一行**。如下:
```kotlin
val anObject = makeMyObject()
anObject?.let { // anObject有可能是null所以要先用?判斷
it.doSomething() // it就是anObject在scope內一定不是null
}
```
## also
also的scope裡物件是 it但是不是回傳最後一行是**回傳自己**也就是it。如下
```kotlin
val anObject = makeMyObject()
anObject?.also { // anObject有可能是null所以要先用?判斷
it.doSomething() // it就是anObject在scope內一定不是null
}.also {
it.doSomething2() // it就是anObject
}.also {
it.doSomething3() // it就是anObject
}
```
## apply
apply的scope裡物件是 this但是不是回傳最後一行是**回傳自己**也就是it。如下
```kotlin
val anObject = makeMyObject()
anObject?.also { // anObject有可能是null所以要先用?判斷
it.doSomething() // it就是anObject在scope內一定不是null
}.also {
it.doSomething2() // it就是anObject
}.also {
it.doSomething3() // it就是anObject
}
```