Sobes.tech
Middle

What is the difference between the extension functions let, run, also, and apply in Kotlin?

sobes.tech AI

Answer from AI

let: Calls a closure on an object and returns the result of the closure. Allows using the object as an argument in a lambda expression (it). Suitable for working with nullable objects.

// Example of using let
val nullableString: String? = "Hello"
val length = nullableString?.let {
    // it is a non-null String
    it.length
}

run: Executes a block of code on an object and returns the result of the block. Inside the block, the object is accessible as this. Useful for initializing an object and then calling methods.

// Example of using run
val result = buildString {
    // this is a StringBuilder
    append("Start\n")
    append("Middle\n")
}.run {
    // this is a String
    uppercase()
}

also: Executes a closure on an object and returns the object itself. Allows performing additional actions (e.g., logging or configuration) on the object without modifying it.

// Example of using also
val list = mutableListOf("a", "b", "c").also {
    // it is a MutableList
    println("List created: $it")
}

apply: Executes a closure on an object and returns the object itself. Inside the block, the object is accessible as this. Convenient for setting properties of an object.

// Example of using apply
val textView = TextView(context).apply {
    // this is a TextView
    text = "Hello, world!"
    textSize = 16f
    setTextColor(Color.BLACK)
}

Main differences:

Function How the object is accessed What it returns Typical use
let it Result of lambda Nullable objects, transformation
run this Result of lambda Initialization and method calls
also it The object itself Additional actions (side effects)
apply this The object itself Setting properties
What is the difference between the extension… - sobes.tech