スコープ関数/kotlin
https://kotlinlang.org/docs/scope-functions.html
Scope functions don't introduce any new technical capabilities, but they can make your code more concise and readable.
糖衣構文ってことかな
スコープ関数の一覧
let
apply
run
also
with
どれもスコープを生成し、新しく変数を定義することなく処理を開始できる
使い分け
Executing a lambda on non-null objects: let
Introducing an expression as a variable in local scope: let
Object configuration: apply
Object configuration and computing the result: run
Running statements where an expression is required: non-extension run
Additional effects: also
Grouping function calls on an object: with
code:kotlin
val adam = Person("Adam").apply {
age = 20 // same as this.age = 20
city = "London"
}
println(adam)
これ初見で見たら絶対混乱するなぁ
age,cityがPersonのメンバ変数であると知るには、applyの挙動を理解している必要がある
文脈から予測はできる
慣れたらすごく直感的だけど
初見で理解しづらい構文