0
0
Kotlinprogramming~20 mins

Interface declaration and implementation in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Interface Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of interface method call
What is the output of this Kotlin code when calling greet() on an instance of FriendlyPerson?
Kotlin
interface Greeter {
    fun greet(): String
}

class FriendlyPerson : Greeter {
    override fun greet(): String {
        return "Hello, friend!"
    }
}

fun main() {
    val person: Greeter = FriendlyPerson()
    println(person.greet())
}
AHello, world!
BCompilation error: greet() not implemented
CHello, friend!
DRuntime error: NullPointerException
Attempts:
2 left
💡 Hint
Check how the greet() method is implemented in the class.
🧠 Conceptual
intermediate
1:30remaining
Interface property declaration
Which of the following is a valid way to declare a read-only property in a Kotlin interface?
Ainterface Vehicle { var wheels: Int = 4 }
Binterface Vehicle { val wheels: Int }
Cinterface Vehicle { fun wheels(): Int = 4 }
Dinterface Vehicle { val wheels: Int = 4 }
Attempts:
2 left
💡 Hint
Interfaces can declare properties without initial values.
🔧 Debug
advanced
2:00remaining
Identify the error in interface implementation
What error will this Kotlin code produce?
Kotlin
interface Speaker {
    fun speak()
}

class Person : Speaker {
    fun speak() {
        println("Hi!")
    }
}

fun main() {
    val p = Person()
    p.speak()
}
ACompilation error: 'speak' in 'Person' hides member of supertype 'Speaker' and needs 'override' modifier
BRuntime error: Method not found
CNo error, prints 'Hi!'
DCompilation error: Interface cannot have methods without body
Attempts:
2 left
💡 Hint
Check if the method correctly overrides the interface method.
Predict Output
advanced
2:30remaining
Multiple interface inheritance output
What is the output of this Kotlin code?
Kotlin
interface A {
    fun hello() = "Hello from A"
}

interface B {
    fun hello() = "Hello from B"
}

class C : A, B {
    override fun hello(): String {
        return super<A>.hello() + " & " + super<B>.hello()
    }
}

fun main() {
    val c = C()
    println(c.hello())
}
AHello from A & Hello from B
BHello from B & Hello from A
CRuntime error: StackOverflowError
DCompilation error: Ambiguous call to hello()
Attempts:
2 left
💡 Hint
Look at how the class C calls the super implementations explicitly.