Why would you use apply in Kotlin?

Technology CommunityCategory: KotlinWhy would you use apply in Kotlin?
VietMX Staff asked 3 years ago

Look at this code:

person.name = "Tony Stark"
person.age = 52

and equivalent with apply will be:

val person = Person().apply {
    name = "Tony Stark" // this. can be omitted
    age = 52 // this. can be omitted
    // ...
}

This way you don’t have to repeat person several times. Apply is used to keep things that belong together in one place (mostly initializations).