Files
Obsidian-Main/03. Programming/Kotlin/run, let, with, also 和 apply.md
Awin Huang 5ee739faf9 vault backup: 2022-09-30 21:13:03
Affected files:
.obsidian/workspace
03. Programming/Kotlin/class.md
03. Programming/Kotlin/run, let, with, also 和 apply.md
2022-09-30 21:13:03 +08:00

23 lines
809 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
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
}
```