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 tolet, but the lambda is called with the object asthis, 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 withthis, returns the object. Often used for configuring an object:val paint = Paint().apply { color = Color.RED strokeWidth = 10f }
In brief:
letandalsowork withit,runandapplywork withthis.letandrunreturn the result of the lambda.alsoandapplyreturn the original object.
This allows choosing the appropriate method depending on the task: transformation, configuration, side effects, etc.