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 arguments1data class Config(var host: String = "", var port: Int = 0)2 // Inside apply, this is the new Config; apply returns it3val config = Config().apply { // Assign properties without writing this. or the variable name4 host = "localhost"5 port = 80806}7 // The data class toString() prints Config(host=localhost, port=8080)8println(config)Output
Config(host=localhost, port=8080)
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