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
This commit is contained in:
@@ -39,7 +39,7 @@ class VerySimple(val para1: Int, val para2: String ) {
|
||||
}
|
||||
```
|
||||
|
||||
## init區塊
|
||||
## `init` 區塊
|
||||
`init`是個優先權高於「主要constructor」的執行區塊,如下:
|
||||
```kotlin
|
||||
class VerySimple(val para1: Int, val para2: String ) {
|
||||
|
||||
22
03. Programming/Kotlin/run, let, with, also 和 apply.md
Normal file
22
03. Programming/Kotlin/run, let, with, also 和 apply.md
Normal file
@@ -0,0 +1,22 @@
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user