Challenge - 5 Problems
Anonymous Object Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of an anonymous object with overridden method
What is the output of this Kotlin code using an anonymous object?
Kotlin
val obj = object { fun greet() = "Hello from anonymous object" } println(obj.greet())
Attempts:
2 left
💡 Hint
Anonymous objects can have functions and properties just like regular classes.
✗ Incorrect
The anonymous object defines a function greet() which returns the string. Calling greet() prints that string.
🧠 Conceptual
intermediate2:00remaining
Type of anonymous object when assigned to a variable
Consider this Kotlin code snippet:
val obj = object {
val x = 10
}
What is the static type of 'obj'?
Attempts:
2 left
💡 Hint
When assigned to a val, the compiler infers the full anonymous object type.
✗ Incorrect
When an anonymous object is assigned to a variable, its full type including properties is preserved.
❓ Predict Output
advanced2:00remaining
Output when anonymous object is returned from a function
What is the output of this Kotlin code?
Kotlin
fun create() = object { val name = "Kotlin" fun greet() = "Hello, $name!" } val obj = create() println(obj.greet())
Attempts:
2 left
💡 Hint
Functions returning anonymous objects have their type erased to Any unless explicitly typed.
✗ Incorrect
When a function returns an anonymous object without an explicit type, the caller sees it as Any, so greet() is not accessible.
🔧 Debug
advanced2:00remaining
Why does this anonymous object code cause a compilation error?
Identify the cause of the compilation error in this Kotlin code:
val obj: Any = object {
fun sayHi() = "Hi"
}
println(obj.sayHi())
Kotlin
val obj: Any = object { fun sayHi() = "Hi" } println(obj.sayHi())
Attempts:
2 left
💡 Hint
Check the declared type of obj and what methods it exposes.
✗ Incorrect
The variable obj is declared as type Any, which does not have sayHi(), so calling obj.sayHi() causes a compilation error.
🚀 Application
expert2:00remaining
Using anonymous objects to implement an interface
What is the output of this Kotlin code?
Kotlin
interface Speaker { fun speak(): String } val speaker = object : Speaker { override fun speak() = "I am anonymous" } println(speaker.speak())
Attempts:
2 left
💡 Hint
Anonymous objects can implement interfaces and override their methods.
✗ Incorrect
The anonymous object implements Speaker and overrides speak(), so calling speak() prints the returned string.