Affected files: .obsidian/workspace 03. Programming/Kotlin/class.md 03. Programming/Kotlin/run, let, with, also 和 apply.md
23 lines
809 B
Markdown
23 lines
809 B
Markdown
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
|
||
}
|
||
```
|
||
|