diff --git a/.obsidian/daily-notes.json b/.obsidian/daily-notes.json index feb1668..ed5a618 100644 --- a/.obsidian/daily-notes.json +++ b/.obsidian/daily-notes.json @@ -1,5 +1,5 @@ { "folder": "01. 個人/01. Daily", "format": "YYYY-MM-DD(ddd)", - "template": "03. 資料收集/99. templates/日記" + "template": "04. 資料收集/99. templates/日記" } \ No newline at end of file diff --git a/.obsidian/templates.json b/.obsidian/templates.json index 66aee99..c50ae14 100644 --- a/.obsidian/templates.json +++ b/.obsidian/templates.json @@ -1,5 +1,5 @@ { - "folder": "03. 資料收集/99. templates", + "folder": "04. 資料收集/99. templates", "dateFormat": "YYYY-MM-DD", "timeFormat": "HH:mm:ss" } \ No newline at end of file diff --git a/03. Programming/Kotlin/run, let, with, also 和 apply.md b/03. Programming/Kotlin/run, let, with, also 和 apply.md index 97160fd..85d0e83 100644 --- a/03. Programming/Kotlin/run, let, with, also 和 apply.md +++ b/03. Programming/Kotlin/run, let, with, also 和 apply.md @@ -1,6 +1,16 @@ `run`, `let`, `with`, `also` 和 `apply` 這幾個都是可以搭配 object 使用的函數,它們之間的差異不大,主要是讓程式看起來更符合語意。 以下解釋各個的差別。 +## 歸納 +| | 變數名稱 | 自訂變數名稱 | 回傳 | +|:--------------:|:----------:|:------------:|:--------:| +| `run()` | | | 最後一行 | +| `with()` | `this` | No | 最後一行 | +| `object.run` | `this` | No | 最後一行 | +| `object.let` | `it` | Yes | 最後一行 | +| `object.also` | `it` | Yes | `this` | +| `object.apply` | `this` | No | `this` | + ## run `run` 後面的區塊會**回傳「最後一行」**,所以可以進行「串接」。如下: ```kotlin @@ -52,7 +62,7 @@ anObject?.also { // anObject有可能是null,所以要先用?判斷 ``` ## object.apply -apply的scope裡,物件是 this,不可以自訂變數名稱,但是不是回傳最後一行,是**回傳自己**(也就是it)。如下: +`apply` 的 scope 裡,物件是 `this`,不可以自訂變數名稱,但是不是回傳最後一行,是**回傳自己**(也就是 `this`)。如下: ```kotlin val anObject = makeMyObject() anObject?.also { // anObject有可能是null,所以要先用?判斷 @@ -62,4 +72,9 @@ anObject?.also { // anObject有可能是null,所以要先用?判斷 }.also { this.doSomething3() // this就是anObject } -``` \ No newline at end of file +``` + +## 參考 +- [簡介 Kotlin: run, let, with, also 和 apply | by Ray Yuan Liou | Medium](https://louis383.medium.com/%E7%B0%A1%E4%BB%8B-kotlin-run-let-with-also-%E5%92%8C-apply-f83860207a0c) +- [Kotlin 的 scope function: apply, let, run..等等 | 只放拖鞋的鞋櫃](https://jchu.cc/2018/05/05-kotlin.html) +- [Kotlin 線上讀書會 筆記 (五) apply、let、run、with、also和takeIf | by Evan Chen | Evan Android Note | Medium](https://medium.com/evan-android-note/kotlin-%E7%B7%9A%E4%B8%8A%E8%AE%80%E6%9B%B8%E6%9C%83-%E7%AD%86%E8%A8%98-%E4%BA%94-apply-let-run-with-also%E5%92%8Ctakeif-2c09d42b09b5) \ No newline at end of file