Apply
We have already discussed apply()
in previous chapters. It returns the same object it operates on and sets the context to this
. The most useful case for this function is setting the fields of a mutable object.
Think of how many times you had to create a class with an empty constructor, then call a lot of setters, one after another:
class JamesBond { lateinit var name: String lateinit var movie: String lateinit var alsoStarring: String } val agentJavaWay = JamesBond() agentJavaWay.name = "Sean Connery" agentJavaWay.movie = "Dr. No"
We can set only name
and movie
, but leave alsoStarring
blank, like this:
val `007` = JamesBond().apply { this.name = "Sean Connery" this.movie = "Dr. No" } println(`007`.name)
Since the context is set to this, we can simplify it to the following nice syntax:
val `007` = JamesBond().apply { name = "Sean Connery" movie = "Dr. No" }
This function is especially good when you work with Java classes that usually have a lot of setters.