0
0
Kotlinprogramming~20 mins

Object expressions (anonymous objects) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Anonymous Object Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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())
AHello from anonymous object
BCompilation error: anonymous object cannot have functions
Cnull
DRuntime error: Unresolved reference greet
Attempts:
2 left
💡 Hint
Anonymous objects can have functions and properties just like regular classes.
🧠 Conceptual
intermediate
2: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'?
AAny
BInt
CUnit
DThe exact anonymous object type with property 'x'
Attempts:
2 left
💡 Hint
When assigned to a val, the compiler infers the full anonymous object type.
Predict Output
advanced
2: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())
ACompilation error: Cannot access greet() on anonymous object returned from function
BHello, $name!
CHello, Kotlin!
DRuntime error: Unresolved reference greet
Attempts:
2 left
💡 Hint
Functions returning anonymous objects have their type erased to Any unless explicitly typed.
🔧 Debug
advanced
2: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())
AAnonymous objects cannot have functions
BThe variable obj is typed as Any, which does not have sayHi() method
CMissing parentheses when calling sayHi
DCannot assign anonymous object to Any type
Attempts:
2 left
💡 Hint
Check the declared type of obj and what methods it exposes.
🚀 Application
expert
2: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())
ARuntime error: speak() not implemented
BCompilation error: anonymous object must implement all interface methods
CI am anonymous
DI am Speaker
Attempts:
2 left
💡 Hint
Anonymous objects can implement interfaces and override their methods.