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

}
Daniel Perez-Gomez

Hi there! 👋 I'm an Android developer currently based in New York City. I write mostly about Android development using Kotlin as well as other programming bits. I'm committed to making this complex field fun and accessible to beginners through my guides and tutorials. I'm also driven by the belief in technology's power to enhance lives, which motivates me to develop apps that are both user-friendly and prioritize accessibility, catering to various needs. Additionally, I host a YouTube channel, “Daniel Talks Code”, where I break down complex concepts into easy-to-follow instructions. Join me in my quest to make the world of Android development inclusive and accessible for all!

Previous
Previous

Perform additional tasks with an object using .also

Next
Next

What is State in programming?