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 Logger1object Logger { // Internal storage that cannot be accessed from outside2 private val logs = mutableListOf<String>()3 // Adds a message to the log4 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 message8 fun printAll() { // One line per message, in the order they were added9 logs.forEach { println(it) }10 }11}12 // Stored as [0] App started13Logger.log("App started")// The same list is used, so this becomes [1] User logged in14Logger.log("User logged in")// Stored as [2] Data loaded15Logger.log("Data loaded")// Prints the three lines16Logger.printAll()Output
[0] App started [1] User logged in [2] Data loaded
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