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 instance
1object Logger {
// Mutable log level, initially "INFO"
2 var level = "INFO"
3
// Method that prints a message prefixed with the current level
4 fun log(msg: String) {
// For example [INFO] Started
5 println("[$level] $msg")
6 }
7}
8
// Call directly through the name, with no instance creation: prints [INFO] Started
9Logger.log("Started")
// Change the singleton's state
10Logger.level = "DEBUG"
// The change persists: prints [DEBUG] Details
11Logger.log("Details")

Output

[INFO] Started
[DEBUG] Details
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.

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

More Kotlin examples at level 4

← Kotlin typing practice