also scope function in Kotlin

Level 3119 keystrokes

also passes the object to the block as it and returns the same object, so it fits side effects such as logging inside a call chain. Here it prints the list before and after adding 4.

Kotlin code

// The chain starts from a mutable list; nums gets the object returned by the last also
1val nums = mutableListOf(1, 2, 3)
// it is the list: prints Initial: [1, 2, 3] and passes the list on unchanged
2 .also { println("Initial: $it") }
// Modify the same list: add 4 (add's return value is ignored)
3 .also { it.add(4) }
// Print Final: [1, 2, 3, 4]
4 .also { println("Final: $it") }

Output

Initial: [1, 2, 3]
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.

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

More Kotlin examples at level 3

← Kotlin typing practice