Daniel Talks Code

View Original

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