apply scope function in Kotlin

Level 389 keystrokes

apply runs a block with the object as this and then returns the object itself. It is handy for setting up an object right after creating it, here filling a list with 1, 2 and 3.

Kotlin code

// Create an empty MutableList<Int>; inside apply, this is that list
1val list = mutableListOf<Int>().apply {
// add() is called on the list without writing this.
2 add(1)
3 add(2)
4 add(3)
// apply returns the list itself, so list is [1, 2, 3]
5}
// Print 1, 2 and 3, one per line
6for (n in list) println(n)

Output

1
2
3
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
  • )× 6
  • .× 1
  • {× 1
  • }× 1
  • <× 1
  • =× 1
  • >× 1

More Kotlin examples at level 3

← Kotlin typing practice