0
0
Kotlinprogramming~10 mins

Object expressions (anonymous objects) in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an anonymous object with a property name.

Kotlin
val obj = object {
    val [1] = "Kotlin"
}
println(obj.name)
Drag options to blanks, or click blank then click option'
Atype
Bvalue
Cname
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different property name like value or type will cause an error when accessing obj.name.
2fill in blank
medium

Complete the code to override the toString() method in an anonymous object.

Kotlin
val obj = object {
    override fun [1](): String {
        return "Anonymous Object"
    }
}
println(obj.toString())
Drag options to blanks, or click blank then click option'
AtoString
Bequals
ChashCode
Dcopy
Attempts:
3 left
💡 Hint
Common Mistakes
Overriding equals or hashCode instead of toString will not change the printed output.
3fill in blank
hard

Fix the error in the code by completing the anonymous object declaration that implements the interface Runnable.

Kotlin
val runnable = object : [1] {
    override fun run() {
        println("Running")
    }
}
runnable.run()
Drag options to blanks, or click blank then click option'
ACallable
BRunnable
CThread
DExecutor
Attempts:
3 left
💡 Hint
Common Mistakes
Using Callable or Thread instead of Runnable causes type errors.
4fill in blank
hard

Fill both blanks to create an anonymous object with a property and a method.

Kotlin
val obj = object {
    val [1] = 10
    fun [2]() = [1] * 2
}
println(obj.doubleValue())
Drag options to blanks, or click blank then click option'
Avalue
BdoubleValue
Cnumber
Dcalculate
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the property or method than those called causes errors.
5fill in blank
hard

Fill all three blanks to create an anonymous object that implements an interface and overrides a method.

Kotlin
interface Greeter {
    fun greet(): String
}

val greeter = object : [1] {
    override fun [2]() = "Hello, [3]!"
}
println(greeter.greet())
Drag options to blanks, or click blank then click option'
AGreeter
Bgreet
CWorld
DGreeting
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong interface or method names causes compilation errors.