Bird
Raised Fist0
Kotlinprogramming~20 mins

Extensions on built-in types in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Kotlin Extensions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of extension function on String
What is the output of this Kotlin code that uses an extension function on a String?
Kotlin
fun String.addExclamation(): String {
    return this + "!"
}

fun main() {
    val greeting = "Hello"
    println(greeting.addExclamation())
}
ACompilation error
BHello
CHELLO!
DHello!
Attempts:
2 left
💡 Hint
Look at how the extension function adds an exclamation mark to the original string.
❓ Predict Output
intermediate
2:00remaining
Extension function on List with condition
What is the output of this Kotlin code that defines an extension function on List to sum only even numbers?
Kotlin
fun List<Int>.sumEven(): Int {
    return this.filter { it % 2 == 0 }.sum()
}

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    println(numbers.sumEven())
}
A9
B10
C6
DCompilation error
Attempts:
2 left
💡 Hint
Sum only the even numbers: 2 and 4.
🔧 Debug
advanced
2:00remaining
Why does this extension function cause a compilation error?
This Kotlin code tries to add an extension function to Int to check if it is prime. Why does it cause a compilation error?
Kotlin
fun Int.isPrime(): Boolean {
    if (this < 2) return false
    for (i in 2 until this) {
        if (this % i == 0) return false
    }
    return true
}

fun main() {
    val number = 7
    println(number.isPrime())
}
ANo error, code compiles and prints true
BError because extension functions cannot be defined on Int
CError because 'until' is not imported
DError because 'this' cannot be used in extension functions
Attempts:
2 left
💡 Hint
Extension functions can be defined on any type including Int.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this extension function
Which option shows the correct syntax for an extension function on String that returns the first character?
Kotlin
fun String.firstChar(): Char {
    return this[0]
}
Afun String.firstChar: Char { return this[0] }
Bfun String.firstChar() = this[0]
Cfun firstChar(this: String): Char = this[0]
Dfun String.firstChar() { return this[0] }
Attempts:
2 left
💡 Hint
Extension functions must have the receiver type before the function name.
🚀 Application
expert
3:00remaining
Using extension functions to add behavior to built-in types
You want to add an extension function to List that returns a single string with all elements joined by a comma and space. Which option produces the correct output for listOf("apple", "banana", "cherry")?
Kotlin
fun List<String>.toCommaSeparated(): String {
    // implementation
}

fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    println(fruits.toCommaSeparated())
}
Areturn this.joinToString(", ")
Breturn this.reduce { acc, s -> acc + ", " + s }
Creturn this.joinToString(separator = ",")
Dreturn this.fold("") { acc, s -> acc + s + ", " }
Attempts:
2 left
💡 Hint
Use the built-in joinToString function with proper separator.

Practice

(1/5)
1. What is the main purpose of extension functions in Kotlin?
easy
A. To create new classes that inherit from built-in types
B. To add new functions to existing types without modifying their source code
C. To override existing functions in built-in types
D. To convert one type to another automatically

Solution

  1. Step 1: Understand extension functions concept

    Extension functions allow adding new functions to existing types without changing their original code.
  2. Step 2: Compare options with concept

    Only To add new functions to existing types without modifying their source code correctly describes this purpose. Options B and C talk about inheritance and overriding, which are different concepts. To convert one type to another automatically is unrelated.
  3. Final Answer:

    To add new functions to existing types without modifying their source code -> Option B
  4. Quick Check:

    Extension functions add new behavior without changing original code [OK]
Hint: Remember: extensions add functions, not change classes [OK]
Common Mistakes:
  • Confusing extension functions with inheritance
  • Thinking extensions override existing methods
  • Believing extensions convert types automatically
2. Which of the following is the correct syntax to define an extension function isEven for Int in Kotlin?
easy
A. fun Int.isEven(): Boolean { return this % 2 == 0 }
B. fun isEven(): Boolean { return this % 2 == 0 }
C. fun Int.isEven: Boolean = this % 2 == 0
D. fun isEven(Int): Boolean = Int % 2 == 0

Solution

  1. Step 1: Recall extension function syntax

    Extension functions are declared as fun TypeName.functionName(). Here, Int.isEven() is correct.
  2. Step 2: Check each option

    fun Int.isEven(): Boolean { return this % 2 == 0 } matches the correct syntax. fun isEven(): Boolean { return this % 2 == 0 } misses the receiver type. fun Int.isEven: Boolean = this % 2 == 0 misses parentheses. fun isEven(Int): Boolean = Int % 2 == 0 has wrong parameter syntax.
  3. Final Answer:

    fun Int.isEven(): Boolean { return this % 2 == 0 } -> Option A
  4. Quick Check:

    Extension syntax = fun TypeName.functionName() [OK]
Hint: Extension syntax always starts with fun TypeName.functionName() [OK]
Common Mistakes:
  • Omitting the receiver type before function name
  • Missing parentheses after function name
  • Using parameter instead of receiver for extension
3. What will be the output of this Kotlin code?
fun String.addExclamation() = this + "!"

fun main() {
    val word = "Hello"
    println(word.addExclamation())
}
medium
A. Hello
B. Hello!!
C. Compilation error
D. Hello!

Solution

  1. Step 1: Understand the extension function behavior

    The extension function addExclamation adds an exclamation mark to the string.
  2. Step 2: Trace the main function output

    Calling word.addExclamation() returns "Hello!" which is printed.
  3. Final Answer:

    Hello! -> Option D
  4. Quick Check:

    Extension adds "!" so output is "Hello!" [OK]
Hint: Extension functions act like normal methods on the type [OK]
Common Mistakes:
  • Expecting original string unchanged
  • Thinking extension adds multiple exclamations
  • Assuming syntax error due to extension
4. Identify the error in this Kotlin extension function and fix it:
fun Int.isPositive {
    return this > 0
}
medium
A. Missing parentheses after function name; should be fun Int.isPositive()
B. Extension functions cannot return Boolean
C. The receiver type Int is invalid for extensions
D. The return statement is not allowed in extension functions

Solution

  1. Step 1: Check function declaration syntax

    Extension functions must have parentheses after the function name, even if no parameters.
  2. Step 2: Identify the fix

    Add parentheses: fun Int.isPositive(). Other options are incorrect because Boolean return is allowed, Int is valid receiver, and return statements are allowed.
  3. Final Answer:

    Missing parentheses after function name; should be fun Int.isPositive() -> Option A
  4. Quick Check:

    Extension functions need () after name [OK]
Hint: Always add () after extension function name, even if no parameters [OK]
Common Mistakes:
  • Omitting parentheses after function name
  • Thinking extensions can't return values
  • Confusing receiver type validity
5. You want to create an extension function wordCount for String that returns the number of words separated by spaces. Which implementation correctly handles multiple spaces and empty strings?
hard
A. fun String.wordCount() = this.split(" ").size
B. fun String.wordCount() = this.count { it == ' ' }
C. fun String.wordCount() = this.trim().split(" ").filter { it.isNotEmpty() }.size
D. fun String.wordCount() = this.length

Solution

  1. Step 1: Understand the problem requirements

    We need to count words separated by spaces, ignoring extra spaces and empty strings.
  2. Step 2: Analyze each option

    fun String.wordCount() = this.split(" ").size splits by space but counts empty strings if multiple spaces exist. fun String.wordCount() = this.trim().split(" ").filter { it.isNotEmpty() }.size trims, splits, filters out empty strings, then counts, correctly handling multiple spaces and empty strings. fun String.wordCount() = this.length returns string length, unrelated. fun String.wordCount() = this.count { it == ' ' } counts spaces, not words.
  3. Final Answer:

    fun String.wordCount() = this.trim().split(" ").filter { it.isNotEmpty() }.size -> Option C
  4. Quick Check:

    Trim, split, filter empty = correct word count [OK]
Hint: Trim and filter empty strings after split to count words correctly [OK]
Common Mistakes:
  • Counting empty strings as words
  • Using string length instead of word count
  • Counting spaces instead of words
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard