Configuring an object with apply in Kotlin

Level 4140 keystrokes

apply runs a block with the object as this and returns the object, so properties can be set right after construction without repeating the variable name. The data class's toString() then shows the values.

Kotlin code

// A data class with var properties and default values, so Config() needs no arguments
1data class Config(var host: String = "", var port: Int = 0)
2
// Inside apply, this is the new Config; apply returns it
3val config = Config().apply {
// Assign properties without writing this. or the variable name
4 host = "localhost"
5 port = 8080
6}
7
// The data class toString() prints Config(host=localhost, port=8080)
8println(config)

Output

Config(host=localhost, port=8080)
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.

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

More Kotlin examples at level 4

← Kotlin typing practice