also()

Like run(), also() is a bit of a “mash-up” of let() and apply() features. Like let(), the object you call also() on is made available as a parameter to your lambda expression, so you can refer to it as it or some custom name. Like apply(), though, also() returns the object you call it on.

data class IntPropertyBag(private val pieces: MutableMap<String, Int> = mutableMapOf()) {
  fun set(key: String, value: Int) {
    pieces[key] = value
  }
}


fun main() {
  val ultimateStuff = IntPropertyBag().also {
    it.set("ID", 330258648)
    it.set("YEAR", 1979)
    it.set("HOW_MANY_ROADS_MUST_A_MAN_WALK_DOWN", 42)
  }

  println(ultimateStuff)
}

In summary, also():


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.