Skip to content

Instantly share code, notes, and snippets.

@xpepper
Created June 26, 2019 16:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpepper/cfa994b6a8d477a1c456dda4cd1ea6f1 to your computer and use it in GitHub Desktop.
Save xpepper/cfa994b6a8d477a1c456dda4cd1ea6f1 to your computer and use it in GitHub Desktop.
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