Side effects in a chain with also in Kotlin

Level 4154 keystrokes

also passes the object to its block as it and returns that same object, so each step in the chain works on one list. numbers ends up referring to the list after 4 has been added.

Kotlin code

// Start the chain with a mutable list; numbers gets what the last also returns
1val numbers = mutableListOf(1, 2, 3)
// it is the list: prints Original: [1, 2, 3]
2 .also { println("Original: $it") }
// Add 4 to the same list; also still returns the list, not add's Boolean
3 .also { it.add(4) }
// Print Modified: [1, 2, 3, 4]
4 .also { println("Modified: $it") }
5
// numbers is that same list: prints Final: [1, 2, 3, 4]
6println("Final: $numbers")

Output

Original: [1, 2, 3]
Modified: [1, 2, 3, 4]
Final: [1, 2, 3, 4]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • "× 6
  • (× 5
  • )× 5
  • .× 4
  • :× 3
  • {× 3
  • }× 3
  • $× 3
  • ,× 2
  • =× 1

More Kotlin examples at level 4

← Kotlin typing practice