Challenge - 5 Problems
Extension Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of extension function call
What is the output of this Kotlin code using an extension function?
Kotlin
fun String.shout() = this.uppercase() + "!" fun main() { val word = "hello" println(word.shout()) }
Attempts:
2 left
💡 Hint
Remember extension functions can add new behavior without changing the original class.
✗ Incorrect
The extension function shout() converts the string to uppercase and adds an exclamation mark. It does not modify the original string but returns a new one.
🧠 Conceptual
intermediate2:00remaining
Why extensions don't modify original class
Why do Kotlin extension functions add functionality without modifying the original class?
Attempts:
2 left
💡 Hint
Think about how extensions are compiled and how they access the receiver.
✗ Incorrect
Kotlin extensions are compiled as static functions with the receiver passed as a parameter. They do not alter the original class's code or state, so the original class remains unchanged.
🔧 Debug
advanced2:30remaining
Why does this extension not change the original list?
Consider this Kotlin code. Why does the original list remain unchanged after calling the extension function?
Kotlin
fun MutableList<Int>.addOne() { this.map { it + 1 } } fun main() { val numbers = mutableListOf(1, 2, 3) numbers.addOne() println(numbers) }
Attempts:
2 left
💡 Hint
Check what map() does to the list and if it changes the original.
✗ Incorrect
The map function creates and returns a new list with transformed elements but does not change the original list. The extension function does not assign or modify the original list, so it stays the same.
📝 Syntax
advanced2:00remaining
Which extension function syntax is correct?
Which of the following Kotlin extension function definitions is syntactically correct?
Attempts:
2 left
💡 Hint
Remember the syntax for extension functions includes the receiver type before the function name.
✗ Incorrect
Option B correctly defines an extension function on Int using the receiver syntax and expression body. Options B, C, and D have syntax errors or missing return statements.
🚀 Application
expert3:00remaining
How to add a new behavior to a class without inheritance or modification?
You want to add a new function to the Kotlin String class that returns the string reversed with dashes between characters. You cannot modify the String class or create a subclass. Which approach is best?
Attempts:
2 left
💡 Hint
Think about how Kotlin allows adding functions without changing original classes or inheritance.
✗ Incorrect
Extension functions let you add new behaviors to existing classes without inheritance or modifying their source. This is the cleanest and safest way to add functionality like this.