Perform additional tasks with an object using .also

If you're looking to do additional tasks with an object after or even while creating an instance of it, take a look at the .also scope function. It takes the object as a parameter for you to use within the corresponding lambda (using the keyword "it") and then returns the object itself. This one should not be used if you're wanting to access the object's members, but if you want to use just the object itself, then it works perfectly. Take a look at the example below:

data class BoxOfCookies(
    val flavor1: String,
    val flavor2: String,
    val flavor3: String,
)

class SalesDept() {
    fun box(cookies: BoxOfCookies) {
        println("$cookies are now in a 🎁")
    }

    fun sell(cookies: BoxOfCookies) {
        println("$cookies have been sold 🤑")
    }

    fun ship(cookies: BoxOfCookies) {
        println("$cookies are now shipped 🚚")
    }
}

fun main(args: Array) {

    val salesDept = SalesDept()
    val myCookies = BoxOfCookies(
        "🍪",
        "ginger snap",
        "oatmeal raisin",
    )
        .also {
            salesDept.box(it)
            salesDept.sell(it)
            salesDept.ship(it)
        }
}
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

Use .run to init objects and perform calculations in one go

Next
Next

.apply is for building things