Bird
Raised Fist0
Android Kotlinmobile~20 mins

Extension functions in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Extension Functions Demo
This screen demonstrates how to use Kotlin extension functions to add new behavior to existing classes without modifying them.
Target UI
-------------------------
| Extension Functions Demo |
|-----------------------|
| Enter text:           |
| [______________]      |
|                       |
| [Show Length]         |
|                       |
| Length:               |
|                       |
-------------------------
Add an EditText for user input
Add a Button labeled 'Show Length'
Add a TextView to display the length of the input text
Create a Kotlin extension function on String to return its length as a formatted string
When the button is clicked, use the extension function to show the length in the TextView
Starter Code
Android Kotlin
package com.example.extensiondemo

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val inputEditText = findViewById<EditText>(R.id.inputEditText)
        val showLengthButton = findViewById<Button>(R.id.showLengthButton)
        val lengthTextView = findViewById<TextView>(R.id.lengthTextView)

        // TODO: Implement button click to show length using extension function
    }
}

// TODO: Create extension function on String here
Task 1
Task 2
Solution
Android Kotlin
package com.example.extensiondemo

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val inputEditText = findViewById<EditText>(R.id.inputEditText)
        val showLengthButton = findViewById<Button>(R.id.showLengthButton)
        val lengthTextView = findViewById<TextView>(R.id.lengthTextView)

        showLengthButton.setOnClickListener {
            val inputText = inputEditText.text.toString()
            lengthTextView.text = inputText.formattedLength()
        }
    }
}

fun String.formattedLength(): String {
    return "Length: ${this.length}"
}

We created an extension function formattedLength on the String class. This function returns a string showing the length of the string in a friendly format.

In the MainActivity, when the user taps the 'Show Length' button, we get the text from the EditText, call the extension function on it, and display the result in the TextView. This shows how extension functions let us add new behavior to existing classes without changing their code.

Final Result
Completed Screen
-------------------------
| Extension Functions Demo |
|-----------------------|
| Enter text:           |
| [Hello Kotlin!]       |
|                       |
| [Show Length]         |
|                       |
| Length: 13            |
|                       |
-------------------------
User types text in the input field
User taps 'Show Length' button
TextView updates to show 'Length: X' where X is the number of characters typed
Stretch Goal
Add a clear button that resets the input field and length display
💡 Hint
Add another Button labeled 'Clear' and set its OnClickListener to clear the EditText and TextView text

Practice

(1/5)
1. What is the main purpose of an extension function in Kotlin?
easy
A. To override existing functions in a class
B. To create a new subclass from an existing class
C. To add new functions to existing classes without modifying them
D. To delete functions from a class

Solution

  1. Step 1: Understand extension functions

    Extension functions let you add new functions to classes without changing their original code.
  2. Step 2: Compare options

    Only To add new functions to existing classes without modifying them correctly describes this behavior; others describe subclassing, overriding, or deleting, which are different concepts.
  3. Final Answer:

    To add new functions to existing classes without modifying them -> Option C
  4. Quick Check:

    Extension function = Add new functions [OK]
Hint: Extension functions add features without changing original class [OK]
Common Mistakes:
  • Confusing extension functions with inheritance
  • Thinking extension functions override existing methods
  • Believing extension functions can remove class methods
2. Which of the following is the correct syntax to declare an extension function isEven() for Int in Kotlin?
easy
A. fun isEven(): Boolean { return this % 2 == 0 }
B. fun Int.isEven(): Boolean { return this % 2 == 0 }
C. fun Int.isEven: Boolean { return this % 2 == 0 }
D. fun Int.isEven() Boolean = this % 2 == 0

Solution

  1. Step 1: Check extension function syntax

    Extension functions are declared with fun ClassName.functionName(), so fun Int.isEven() is correct.
  2. Step 2: Validate return type and body

    fun Int.isEven(): Boolean { return this % 2 == 0 } correctly uses parentheses and return type with a proper function body.
  3. Final Answer:

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

    Extension syntax = fun ClassName.functionName() [OK]
Hint: Extension syntax always starts with fun ClassName.functionName() [OK]
Common Mistakes:
  • Omitting the receiver type before function name
  • Missing parentheses after function name
  • Incorrect return type declaration
3. What will be the output of this Kotlin code?
fun String.addHello() = "Hello, $this!"

fun main() {
  val name = "Anna"
  println(name.addHello())
}
medium
A. Hello, Anna!
B. AnnaHello, !
C. Hello, !
D. Compilation error

Solution

  1. Step 1: Understand the extension function

    The function addHello() adds "Hello, " before the string and an exclamation mark after.
  2. Step 2: Apply function to variable

    Calling name.addHello() where name is "Anna" returns "Hello, Anna!".
  3. Final Answer:

    Hello, Anna! -> Option A
  4. Quick Check:

    Extension adds prefix and suffix correctly [OK]
Hint: Extension functions run like normal methods on instances [OK]
Common Mistakes:
  • Misreading string interpolation syntax
  • Assuming extension modifies original string
  • Expecting output without exclamation mark
4. Identify the error in this Kotlin extension function code:
fun Int.isPositive() {
  return this > 0
}
medium
A. Function must declare a return type Boolean
B. The function body should not use return
C. The keyword 'this' cannot be used in extension functions
D. Extension function cannot be declared on Int

Solution

  1. Step 1: Check function return type

    The function returns a Boolean expression but does not declare a return type, which is required.
  2. Step 2: Confirm correct syntax

    Adding : Boolean after the function name fixes the error.
  3. Final Answer:

    Function must declare a return type Boolean -> Option A
  4. Quick Check:

    Return type needed for non-Unit functions [OK]
Hint: Declare return type when function returns a value [OK]
Common Mistakes:
  • Omitting return type for Boolean-returning functions
  • Thinking 'this' is disallowed in extensions
  • Confusing Unit functions with value-returning ones
5. You want to add an extension function toTitleCase() to String that capitalizes the first letter of each word. Which implementation correctly achieves this?
hard
A. fun String.toTitleCase() = this.toUpperCase()
B. fun String.toTitleCase() = this.lowercase()
C. fun String.toTitleCase() = this.replaceFirstChar { it.uppercase() }
D. fun String.toTitleCase() = split(" ").joinToString(" ") { it.capitalize() }

Solution

  1. Step 1: Understand title case requirement

    Title case means capitalizing the first letter of each word, not the whole string or just the first letter.
  2. Step 2: Analyze options

    fun String.toTitleCase() = split(" ").joinToString(" ") { it.capitalize() } splits the string by spaces, capitalizes each word, then joins them back, correctly implementing title case.
  3. Final Answer:

    fun String.toTitleCase() = split(" ").joinToString(" ") { it.capitalize() } -> Option D
  4. Quick Check:

    Title case = capitalize each word [OK]
Hint: Split words, capitalize each, then join for title case [OK]
Common Mistakes:
  • Using uppercase() on whole string instead of each word
  • Capitalizing only first character of entire string
  • Ignoring spaces between 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