Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin Scope Functions
// it's NOT an extension function
// it takes the receiver and a lambda with the same receiver
// it returns the result of the lambda on the implicit receiver
inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    return receiver.block()
}

with ("ciao") {
    length + 1
}

// it's an extension function (can be called on nullable types)
// it takes a lambda with receiver
// it returns the result of the lambda on the implicit receiver
inline fun <T, R> T.run(block: T.() -> R): R {
    return block()
}

val number = 1
val asString = number.run {
    plus(2).toString()
}
println(asString)

// it's an extension function (can be called on nullable types)
// it takes a regular function
// it returns the result of the lambda with the implicit receiver as its argument
inline fun <T, R> T.let(block: (T) -> R): R {
    return block(this);
}

val s: String? = null
s?.let { it: String -> println(it) }

// it's an extension function (can be called on nullable types)
// it takes a lambda with receiver
// it returns the receiver
inline fun <T> T.apply(block: T.() -> Unit): T {
    block()
    return this
}

StringBuilder().apply {
    append("c")
    append("i")
    append("a")
    append("o")
}.toString()

// it's an extension function (can be called on nullable types)
// it takes a regular function with the receiver as its parameter
// it returns the receiver
inline fun <T> T.also(block: (T) -> Unit): T {
    block(this)
    return this
}

val ciao = "ciao".also { println(it.length) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.