Challenge - 5 Problems
Extension Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple 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 that the extension function converts the string to uppercase and adds an exclamation mark.
✗ Incorrect
The extension function shout() converts the string to uppercase and appends an exclamation mark, so "hello" becomes "HELLO!".
🧠 Conceptual
intermediate1:30remaining
Understanding receiver type in extension functions
In Kotlin, what does the receiver type in an extension function represent?
Attempts:
2 left
💡 Hint
Think about what object you are extending when you write an extension function.
✗ Incorrect
The receiver type is the type of the object that the extension function is called on, allowing you to add new functions to that type.
🔧 Debug
advanced2:00remaining
Identify the error in this extension function
What error will this Kotlin code produce?
Kotlin
fun Int.add(x: Int): Int { return this + x } fun main() { val result = 5.add() println(result) }
Attempts:
2 left
💡 Hint
Check how the extension function is called and what parameters it expects.
✗ Incorrect
The extension function add requires one parameter 'x', but the call 5.add() provides none, causing a compilation error.
📝 Syntax
advanced2:00remaining
Correct syntax for extension function with nullable receiver
Which option shows the correct syntax for an extension function on a nullable String receiver that returns its length or zero if null?
Attempts:
2 left
💡 Hint
Remember to use the safe call operator when the receiver can be null.
✗ Incorrect
Option C correctly declares the receiver as nullable String? and uses safe call 'this?.length' to avoid null pointer exceptions.
🚀 Application
expert3:00remaining
Extension function to filter and transform a list
Given this extension function on List, what is the output of the code below?
Kotlin
fun List<Int>.filterAndDouble(predicate: (Int) -> Boolean): List<Int> { val result = mutableListOf<Int>() for (item in this) { if (predicate(item)) { result.add(item * 2) } } return result } fun main() { val numbers = listOf(1, 2, 3, 4, 5) val filtered = numbers.filterAndDouble { it % 2 == 1 } println(filtered) }
Attempts:
2 left
💡 Hint
The predicate filters odd numbers, then doubles them before adding to the result list.
✗ Incorrect
The function filters odd numbers (1,3,5) and doubles them (2,6,10), so the output is [2, 6, 10].