0
0
Kotlinprogramming~10 mins

Companion object with interfaces 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 declare a companion object inside the class.

Kotlin
class MyClass {
    companion object [1] {
        fun greet() = "Hello"
    }
}
Drag options to blanks, or click blank then click option'
Acompanion
BcompanionObject
CCompanionObject
DCompanion
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase 'Companion' instead of lowercase 'companion'.
Trying to name the companion object explicitly without the keyword.
2fill in blank
medium

Complete the code to make the companion object implement the interface.

Kotlin
interface Greeter {
    fun greet(): String
}

class MyClass {
    companion object : [1] {
        override fun greet() = "Hi"
    }
}
Drag options to blanks, or click blank then click option'
AGreeting
BGreeter
CGreetable
DGreets
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong interface name that does not exist.
Forgetting to add the colon before the interface name.
3fill in blank
hard

Fix the error in the companion object declaration to correctly implement the interface.

Kotlin
interface Speaker {
    fun speak(): String
}

class Talk {
    companion object [1] Speaker {
        override fun speak() = "Hello"
    }
}
Drag options to blanks, or click blank then click option'
Aextends
Bimplements
C:
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'implements' like in Java.
Using 'extends' which is for class inheritance.
4fill in blank
hard

Fill both blanks to declare a companion object that implements two interfaces.

Kotlin
interface A {
    fun a()
}
interface B {
    fun b()
}

class Multi {
    companion object [1] [2] {
        override fun a() {}
        override fun b() {}
    }
}
Drag options to blanks, or click blank then click option'
A:
B,
C;
D&
Attempts:
3 left
💡 Hint
Common Mistakes
Using semicolons or ampersands to separate interfaces.
Forgetting the colon before the interface list.
5fill in blank
hard

Fill both blanks to create a companion object that implements an interface and has a function.

Kotlin
interface Logger {
    fun log(message: String)
}

class App {
    companion object : Logger {
        fun info(msg: String) = println(msg)
        override fun log(message: String) = info([1])
    }
}

fun main() {
    App.Companion.log([2])
}
Drag options to blanks, or click blank then click option'
A:
Bmessage
C"App started"
Dmsg
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong symbols instead of colon for interface implementation.
Passing wrong variable names inside the function call.
Not using quotes around the string message.