Challenge - 5 Problems
Kotlin Singleton Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing object properties
What is the output of this Kotlin code using an object declaration?
Kotlin
object Config { val version = 1 val name = "App" } fun main() { println(Config.version) println(Config.name) }
Attempts:
2 left
💡 Hint
Object declarations create a single instance accessible by the name.
✗ Incorrect
The object declaration 'Config' creates a singleton instance. Accessing its properties prints their values.
🧠 Conceptual
intermediate2:00remaining
Why does Kotlin object declaration create a singleton?
Why does an object declaration in Kotlin create a singleton instance?
Attempts:
2 left
💡 Hint
Think about how Kotlin restricts instance creation for object declarations.
✗ Incorrect
Kotlin object declarations create a class with a private constructor and instantiate it once, ensuring only one instance exists.
❓ Predict Output
advanced2:00remaining
Comparing object instances
What is the output of this Kotlin code comparing two references to the same object declaration?
Kotlin
object Logger { fun log(msg: String) = println("Log: $msg") } fun main() { val a = Logger val b = Logger println(a === b) }
Attempts:
2 left
💡 Hint
The '===' operator checks if two references point to the same object.
✗ Incorrect
Since Logger is a singleton object, both 'a' and 'b' refer to the same instance, so 'a === b' is true.
🔧 Debug
advanced2:00remaining
Why does this code fail to compile?
Why does this Kotlin code fail to compile?
Kotlin
object Counter { var count = 0 } fun main() { val c = Counter() println(c.count) }
Attempts:
2 left
💡 Hint
Remember how object declarations are accessed in Kotlin.
✗ Incorrect
Object declarations are singletons and cannot be instantiated using parentheses like classes. They are accessed by their name directly.
🚀 Application
expert3:00remaining
Using object declaration for thread-safe singleton
Which Kotlin object declaration ensures thread-safe lazy initialization of a singleton?
Kotlin
object Database { init { println("Initializing database connection") } fun query(sql: String) = "Result for: $sql" } fun main() { println(Database.query("SELECT * FROM users")) println(Database.query("SELECT * FROM orders")) }
Attempts:
2 left
💡 Hint
Kotlin object declarations are thread-safe by default and initialized on first use.
✗ Incorrect
Kotlin guarantees that object declarations are initialized lazily and in a thread-safe manner when first accessed.