Challenge - 5 Problems
Kotlin Object Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin object declaration?
Consider the following Kotlin code. What will be printed when
Main.main() is run?Kotlin
object Counter { var count = 0 fun increment() { count++ } } fun main() { Counter.increment() Counter.increment() println(Counter.count) }
Attempts:
2 left
💡 Hint
Remember that object declarations create a singleton instance.
✗ Incorrect
The object
Counter is a singleton. Calling increment() twice increases count from 0 to 2. So, printing Counter.count outputs 2.❓ Predict Output
intermediate2:00remaining
What error does this Kotlin object declaration cause?
What error will this Kotlin code produce when compiled?
Kotlin
object Sample { val x: Int } fun main() { println(Sample.x) }
Attempts:
2 left
💡 Hint
Check if properties in objects need initialization.
✗ Incorrect
In Kotlin, properties in objects must be initialized or declared abstract. Here,
x is neither initialized nor abstract, causing a compilation error.🔧 Debug
advanced2:00remaining
Why does this Kotlin object declaration cause a runtime error?
This Kotlin code compiles but throws an exception at runtime. What causes the error?
Kotlin
object Config { val data = loadData() fun loadData(): String { throw IllegalStateException("Failed to load") } } fun main() { println(Config.data) }
Attempts:
2 left
💡 Hint
Object initialization runs when first accessed.
✗ Incorrect
The
data property is initialized by calling loadData(), which throws an exception. This happens during object initialization, causing a runtime exception before main proceeds.📝 Syntax
advanced2:00remaining
Which Kotlin object declaration syntax is correct?
Which of the following Kotlin object declarations is syntactically correct?
Attempts:
2 left
💡 Hint
Check for proper function body braces and object closing brace.
✗ Incorrect
Option C correctly defines a function with braces and closes the object declaration properly. Option C misses braces for function body, C uses invalid lambda syntax for function body, and D misses the closing brace for the object.
🚀 Application
expert2:00remaining
How many instances of this Kotlin object are created?
Given this Kotlin code, how many instances of
Database are created during program execution?Kotlin
object Database { init { println("Database initialized") } fun query() = "data" } fun main() { println(Database.query()) println(Database.query()) }
Attempts:
2 left
💡 Hint
Objects in Kotlin are singletons by design.
✗ Incorrect
Kotlin's object declarations create a single instance (singleton). The
Database object is initialized once when first accessed, so only one instance exists.