Bird
Raised Fist0
Kotlinprogramming~30 mins

Why extensions add without modifying in Kotlin - See It in Action

Choose your learning style10 modes available
Why Extensions Add Without Modifying in Kotlin
📖 Scenario: Imagine you have a simple class representing a book in a library app. You want to add a new feature to get a short description of the book without changing the original class code.
🎯 Goal: You will learn how to use Kotlin extensions to add new functions to an existing class without modifying its original code.
📋 What You'll Learn
Create a class called Book with two properties: title and author
Create an extension function called shortDescription for the Book class
The shortDescription function should return a string combining the title and author
Call the shortDescription function on a Book object and print the result
💡 Why This Matters
🌍 Real World
Extensions let developers add new features to existing classes from libraries or frameworks without changing their source code. This helps keep code clean and flexible.
💼 Career
Knowing how to use Kotlin extensions is useful for Android developers and Kotlin programmers to write cleaner, more maintainable code and extend functionality easily.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with two properties: title of type String and author of type String. Use a primary constructor to set these properties.
Kotlin
Hint

Use class Book(val title: String, val author: String) to create the class with properties.

2
Create an extension function shortDescription
Create an extension function called shortDescription for the Book class. It should return a String combining the book's title and author in this format: "Title by Author".
Kotlin
Hint

Write fun Book.shortDescription(): String { return "$title by $author" } to add the extension function.

3
Create a Book object and call shortDescription
Create a Book object called myBook with title set to "Kotlin Basics" and author set to "Jane Doe". Then call the shortDescription function on myBook and store the result in a variable called description.
Kotlin
Hint

Create the object with val myBook = Book("Kotlin Basics", "Jane Doe") and call myBook.shortDescription().

4
Print the description
Print the variable description to display the short description of the book.
Kotlin
Hint

Use println(description) to show the result.

Practice

(1/5)
1. What is the main reason Kotlin extensions add functionality without modifying the original class?
easy
A. They create new functions outside the class without changing its code
B. They rewrite the original class bytecode
C. They require inheritance from the original class
D. They replace the original class methods at runtime

Solution

  1. Step 1: Understand how extensions work

    Kotlin extensions define new functions outside the original class without altering its source code.
  2. Step 2: Compare with other options

    Options A, B, and D involve modifying or replacing the original class, which extensions do not do.
  3. Final Answer:

    They create new functions outside the class without changing its code -> Option A
  4. Quick Check:

    Extensions add functions externally = C [OK]
Hint: Extensions add functions externally, no class code change [OK]
Common Mistakes:
  • Thinking extensions modify original class code
  • Confusing extensions with inheritance
  • Believing extensions replace methods at runtime
2. Which of the following is the correct syntax to define an extension function greet for the String class in Kotlin?
easy
A. fun greet() = String { println("Hello") }
B. fun greet(String) { println("Hello") }
C. fun greet() String { println("Hello") }
D. fun String.greet() { println("Hello") }

Solution

  1. Step 1: Recall extension function syntax

    Extension functions are declared as fun ClassName.functionName(), so for String: fun String.greet().
  2. Step 2: Validate options

    fun String.greet() { println("Hello") } matches correct syntax. Others have wrong parameter placement or return type.
  3. Final Answer:

    fun String.greet() { println("Hello") } -> Option D
  4. Quick Check:

    Extension syntax = fun ClassName.functionName() [OK]
Hint: Extension syntax: fun ClassName.functionName() [OK]
Common Mistakes:
  • Placing class name as parameter instead of receiver
  • Incorrect return type syntax
  • Using function without receiver type
3. What will be the output of this Kotlin code?
fun String.shout() = this.uppercase() + "!"

fun main() {
    val word = "hello"
    println(word.shout())
}
medium
A. hello!
B. HELLO!
C. Hello!
D. Error: No such function

Solution

  1. Step 1: Understand the extension function

    The extension shout() converts the string to uppercase and adds an exclamation mark.
  2. Step 2: Apply the function to "hello"

    "hello" becomes "HELLO" plus "!" resulting in "HELLO!".
  3. Final Answer:

    HELLO! -> Option B
  4. Quick Check:

    Uppercase + ! = HELLO! [OK]
Hint: Extension adds uppercase and ! to string [OK]
Common Mistakes:
  • Assuming original string unchanged
  • Confusing uppercase with capitalized
  • Expecting runtime error for extension
4. Identify the error in this Kotlin extension function code:
fun Int.addFive() = this + 5

fun main() {
    val number = 10
    println(number.addfive())
}
medium
A. Missing return type in extension function
B. Extension function cannot be defined on Int
C. Function call uses wrong case: addfive() instead of addFive()
D. Cannot call extension function on val variable

Solution

  1. Step 1: Check extension function definition

    The extension addFive() is correctly defined on Int with proper syntax.
  2. Step 2: Check function call in main()

    The call uses addfive() with lowercase 'f', which does not match the defined function name.
  3. Final Answer:

    Function call uses wrong case: addfive() instead of addFive() -> Option C
  4. Quick Check:

    Function names are case-sensitive = A [OK]
Hint: Function names are case-sensitive in Kotlin [OK]
Common Mistakes:
  • Ignoring case sensitivity in function calls
  • Thinking extension can't be on Int
  • Assuming val variables can't use extensions
5. You want to add a function isEven() to the Int class that returns true if the number is even, without modifying the original Int class. Which Kotlin code correctly achieves this and why does it not change the original class?
hard
A. fun Int.isEven() = this % 2 == 0 // Adds function externally without changing Int class
B. class Int { fun isEven() = this % 2 == 0 } // Rewrites Int class
C. fun isEven(n: Int) = n % 2 == 0 // Defines a separate function, not extension
D. Int.isEven = { this % 2 == 0 } // Attempts to assign function to Int class

Solution

  1. Step 1: Identify correct extension syntax

    fun Int.isEven() = this % 2 == 0 defines an extension function on Int using fun Int.isEven(), which is the correct way.
  2. Step 2: Understand why original class is unchanged

    Extensions add functions externally without modifying or rewriting the original Int class bytecode.
  3. Final Answer:

    fun Int.isEven() = this % 2 == 0 // Adds function externally without changing Int class -> Option A
  4. Quick Check:

    Extension adds function externally = D [OK]
Hint: Extensions add functions externally, no class rewrite [OK]
Common Mistakes:
  • Trying to redefine Int class directly
  • Confusing extension with normal function
  • Attempting to assign function to class property
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