Sobes.tech
Junior — Middle

What are the differences between the apply and let functions in the context of scope and usage in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the functions apply and let are scope functions that allow working with objects in a specific context, but they differ in scope and return value.

  • apply executes a block of code with the object as this and returns the object itself. It is often used for object initialization.
val person = Person().apply {
    name = "Ivan"
    age = 30
}
// person is a Person object with set properties
  • let executes a block with the object as it and returns the result of the block. It is convenient for handling nullable values and call chains.
val nameLength = person.name?.let {
    println(it)
    it.length
}
// nameLength is the length of the name or null if name == null

Summary:

  • apply: object is available as this, the object is returned.
  • let: object is available as it, the result of the lambda is returned.