Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different property name like
value or type will cause an error when accessing obj.name.✗ Incorrect
The anonymous object has a property called
name, so you must declare it as val name.2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Overriding
equals or hashCode instead of toString will not change the printed output.✗ Incorrect
To customize the string representation, override the
toString() method.3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
Callable or Thread instead of Runnable causes type errors.✗ Incorrect
To create an anonymous object that implements
Runnable, use object : Runnable.4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the property or method than those called causes errors.
✗ Incorrect
The property is named
value and the method is doubleValue which returns twice the property.5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong interface or method names causes compilation errors.
✗ Incorrect
The anonymous object implements
Greeter, overrides greet(), and returns "Hello, World!".