(c in 'a'..'z') { append(c) } toString() } The with function with is a function val sb = StringBuilder() sb.appendln("Alphabet: ") for (c in 'a'..'z') { sb.append(c) } sb.toString()
(sb) { this.appendln(“Alphabet: ") for (c in 'a'..'z') { this.append(c) } this.toString() } val sb = StringBuilder() with (sb, { -> this.appendln(“Alphabet: ") for (c in 'a'..'z') { this.append(c) } this.toString() }) lambda is its second argument Lambda with receiver with is a function this is an implicit receiver in the lambda val sb = StringBuilder() with (sb) { appendln("Alphabet: ") for (c in 'a'..'z') { append(c) } toString() } this can be omitted
vs lambda with receiver val isEven: (Int) -> Boolean = { it % 2 == 0 } val isOdd: Int.() -> Boolean = { this % 2 == 1 } isEven(0) 1.isOdd() calling as regular function calling as extension function
Unit ): String { val stringBuilder = StringBuilder() ... return stringBuilder.toString() } The buildString function Creates a StringBuilder Calls the specified actions on a stringBuilder Returns String as a result stringBuilder.builderAction()
finally { db.endTransaction() } db.inTransaction { delete("users", "first_name = ?", arrayOf("Jake")) } Inline functions is declared as inline function generated bytecode is similar to
you sure?", message = "Are you really sure?") { positiveButton("Yes") { process() } negativeButton("No") { } }.show() } Are you sure? Are you really sure? No Yes
block: T.() -> R): R = receiver.block() inline fun <T, R> T.run(block: T.() -> R): R = block() inline fun <T, R> T.let(block: (T) -> R): R = block(this) inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this } inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }