Object declaration in Kotlin
Level 4155 keystrokes
object declares a singleton: a class with exactly one instance, created on first use and accessed by its name. Changing Logger.level affects every later log() call.
Kotlin code
// object declares a singleton: Logger is both the type and its only instance1object Logger { // Mutable log level, initially "INFO"2 var level = "INFO"3 // Method that prints a message prefixed with the current level4 fun log(msg: String) { // For example [INFO] Started5 println("[$level] $msg")6 }7}8 // Call directly through the name, with no instance creation: prints [INFO] Started9Logger.log("Started")// Change the singleton's state10Logger.level = "DEBUG"// The change persists: prints [DEBUG] Details11Logger.log("Details")Output
[INFO] Started [DEBUG] Details
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.
"× 10(× 4)× 4.× 3{× 2}× 2=× 2$× 2:× 1[× 1