Illustration of the .apply scope function by Daniel Perez-Gomez

.apply is for building things

March 03, 2021

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()
    }

}

Profile picture

Written by Daniel Perez-Gomez who is currently a Senior Software Engineer in Test working on becoming a front-end software developer. Follow me on Bluesky, GitHub, and YouTube

Comments