Sobes.tech
Junior — Middle

What is the difference between the methods run, let, also, and apply in Kotlin or similar languages?

sobes.tech AI

Answer from AI

In Kotlin, the methods run, let, also, and apply are extension functions with different behaviors and purposes:

  • let: takes an object as a parameter (it), returns the result of the lambda. Often used for safe operations with nullable objects, for example:

    val result = obj?.let { it.doSomething() }
    
  • run: similar to let, but the lambda is called with the object as this, and returns the result of the lambda. Useful for computations and initialization:

    val length = str.run { length }
    
  • also: takes an object as a parameter (it), returns the object itself. Used for additional operations like logging without modifying the object:

    val obj = Obj().also { println(it) }
    
  • apply: lambda with this, returns the object. Often used for configuring an object:

    val paint = Paint().apply {
        color = Color.RED
        strokeWidth = 10f
    }
    

In brief:

  • let and also work with it, run and apply work with this.
  • let and run return the result of the lambda.
  • also and apply return the original object.

This allows choosing the appropriate method depending on the task: transformation, configuration, side effects, etc.