Scope funkce v Kotlinu

Cílem block functions je vykonat blok kódu v kontextu daného kódu. To znamená, že pokud zavoláte takovou funkci na objektu s lambdou, vytvoří se rozsah (scope), ve kterém můžete k objektu přistupovat bez uvedení jeho jména. Tyto funkce se mezi sebou liší tím, jak je možné k objektu v rámci scope přistoupit a jaký je výsledek celého výrazu.

also it kontext objekt Use also for actions that need a reference to the object rather than its properties and functions, or when you don’t want to shadow this reference from an outer scope.
apply this kontext objekt The common case for apply is the object configuration. Such calls can be read as “ apply the following assignments to the object.”
let it výsledek lambdy let can be used to invoke one or more functions on results of call chains.
run this výsledek lambdy run is useful when your lambda contains both the object initialization and the computation of the return value.
with this výsledek lambdy We recommend with for calling functions on the context object without providing the lambda result. In the code, with can be read as “ with this object, do the following.”
val letResult: String = customer
    .let {
        it.name
    }

val runResult: String = customer
    .run {
        name
    }

val withResult: String = with(customer) {
    name
}

val applyResult: Customer = customer
    .apply {
        name
    }

val alsoResult: Customer = customer
    .also {
        it.name
    }

Zdroj: kotlinlang.org/docs/scope-functions.html

Napsat komentář