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.
applyexecutes a block of code with the object asthisand 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
letexecutes a block with the object asitand 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 asthis, the object is returned.let: object is available asit, the result of the lambda is returned.