0
0
Kotlinprogramming~20 mins

Extension function syntax in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Extension Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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())
}
Ahello!
BHELLO!
CHello!
DHELLO
Attempts:
2 left
💡 Hint
Remember that the extension function converts the string to uppercase and adds an exclamation mark.
🧠 Conceptual
intermediate
1:30remaining
Understanding receiver type in extension functions
In Kotlin, what does the receiver type in an extension function represent?
AThe type of the object the extension function is called on
BThe type of the variable inside the extension function
CThe type of the parameter passed to the extension function
DThe return type of the extension function
Attempts:
2 left
💡 Hint
Think about what object you are extending when you write an extension function.
🔧 Debug
advanced
2: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)
}
AError: No value passed for parameter 'x'
BError: Extension function cannot have parameters
CError: 'this' cannot be used in extension functions
DNo error, output is 5
Attempts:
2 left
💡 Hint
Check how the extension function is called and what parameters it expects.
📝 Syntax
advanced
2: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?
Afun String?.lengthOrZero() = length ?: 0
Bfun String.lengthOrZero() = this?.length ?: 0
Cfun String?.lengthOrZero() = this?.length ?: 0
Dfun String?.lengthOrZero() = this.length ?: 0
Attempts:
2 left
💡 Hint
Remember to use the safe call operator when the receiver can be null.
🚀 Application
expert
3: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)
}
A[2, 4, 6, 8, 10]
B[1, 3, 5]
C[1, 2, 3, 4, 5]
D[2, 6, 10]
Attempts:
2 left
💡 Hint
The predicate filters odd numbers, then doubles them before adding to the result list.