.apply is for building things
One of the things I've wanted to improve on is my use of Kotlin Scope functions in my everyday workflow. And so I decided to start a short series where I'll talk about how to use each of the functions along with an example or two.
Starting with the .apply
scope function, it is useful for building objects as it applies the actions within the corresponding lambda to the object that it is called on. It doesn't return a value, but instead you get the object itself. Which means you can both declare a new object and "apply" multiple actions on it at the same time.
class NinjaTurtle(
val name: String,
val color: String,
val weapon: String,
) {
fun training() {
println("$name is now a ninja!")
}
fun feed() {
println("$name loves 🍕!")
}
}
fun main(args: Array) {
val donnie = NinjaTurtle(
"Donatello",
"purple",
"bo"
).apply {
training()
feed()
}
}