Singleton logger with object in Kotlin

Level 5275 keystrokes

object Logger is a singleton, so every call works on the same private list of messages. log() numbers each message with the current list size, and printAll() prints them in order.

Kotlin code

// A singleton: one instance, accessed by the name Logger
1object Logger {
// Internal storage that cannot be accessed from outside
2 private val logs = mutableListOf<String>()
3
// Adds a message to the log
4 fun log(message: String) {
// The size before adding is the number: 0, 1, 2…
5 logs.add("[${logs.size}] $message")
6 }
7
// Prints every stored message
8 fun printAll() {
// One line per message, in the order they were added
9 logs.forEach { println(it) }
10 }
11}
12
// Stored as [0] App started
13Logger.log("App started")
// The same list is used, so this becomes [1] User logged in
14Logger.log("User logged in")
// Stored as [2] Data loaded
15Logger.log("Data loaded")
// Prints the three lines
16Logger.printAll()

Output

[0] App started
[1] User logged in
[2] Data loaded
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.

  • (× 9
  • )× 9
  • "× 8
  • .× 7
  • {× 5
  • }× 5
  • $× 2
  • :× 1
  • [× 1
  • ]× 1

More Kotlin examples at level 5

← Kotlin typing practice