Challenge - 5 Problems
Kotlin Extensions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of extension function call with base type reference
What is the output of this Kotlin code snippet?
Kotlin
open class Animal class Dog : Animal() fun Animal.sound() = "Animal sound" fun Dog.sound() = "Dog sound" fun main() { val animal: Animal = Dog() println(animal.sound()) }
Attempts:
2 left
💡 Hint
Extension functions are resolved based on the declared type, not the runtime type.
✗ Incorrect
In Kotlin, extension functions are resolved statically using the compile-time type of the variable. Here, 'animal' is declared as Animal, so Animal.sound() is called, printing "Animal sound".
❓ Predict Output
intermediate2:00remaining
Extension function call with subclass reference
What will this Kotlin program print?
Kotlin
open class Vehicle class Car : Vehicle() fun Vehicle.describe() = "Vehicle" fun Car.describe() = "Car" fun main() { val car = Car() println(car.describe()) }
Attempts:
2 left
💡 Hint
The variable type is Car, so Car's extension function is called.
✗ Incorrect
Since 'car' is declared as Car, the extension function for Car is called, printing "Car".
🔧 Debug
advanced2:30remaining
Why does this extension function call print unexpected output?
Consider this Kotlin code. Why does it print "Base extension" instead of "Derived extension"?
Kotlin
open class Base class Derived : Base() fun Base.info() = "Base extension" fun Derived.info() = "Derived extension" fun printInfo(b: Base) { println(b.info()) } fun main() { val d = Derived() printInfo(d) }
Attempts:
2 left
💡 Hint
Think about the type of 'b' inside printInfo function.
✗ Incorrect
The parameter 'b' is declared as Base, so the extension function for Base is called, even if the actual object is Derived.
🧠 Conceptual
advanced2:00remaining
Understanding extension function dispatch in Kotlin
Which statement best describes how Kotlin resolves extension functions when called on an object?
Attempts:
2 left
💡 Hint
Consider if extension functions behave like normal class methods.
✗ Incorrect
Kotlin resolves extension functions statically at compile time based on the declared type, not dynamically at runtime.
❓ Predict Output
expert3:00remaining
Output of extension function with nullable receiver and smart cast
What is the output of this Kotlin code?
Kotlin
fun String?.describe() = if (this == null) "Null string" else "String of length ${this.length}" fun main() { val s: String? = null println(s.describe()) val t: String? = "hello" println(t.describe()) }
Attempts:
2 left
💡 Hint
Extension functions can have nullable receivers and handle null safely.
✗ Incorrect
The extension function checks if 'this' is null and returns "Null string" or the length accordingly. So it prints "Null string" then "String of length 5".