Bird
Raised Fist0
Kotlinprogramming~10 mins

Extension function syntax in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Extension function syntax
Define extension function
↓
Call extension function on object
↓
Inside function: 'this' refers to object
↓
Execute function body
↓
Return result or Unit
↓
End
Extension functions add new functions to existing types without changing their code. You define them, then call them on objects as if they were built-in.
Execution Sample
Kotlin
fun String.shout() = this.uppercase() + "!"

val word = "hello"
println(word.shout())
Defines an extension function shout() for String that makes the text uppercase and adds an exclamation mark, then calls it on "hello".
Execution Table
StepActionEvaluationResult
1Define extension function shout() for Stringfun String.shout() = this.uppercase() + "!"Function ready to use
2Create variable wordval word = "hello"word = "hello"
3Call word.shout()word.shout()Calls extension function on "hello"
4Inside shout(): this.uppercase()"hello".uppercase()"HELLO"
5Inside shout(): add "!""HELLO" + "!""HELLO!"
6Return from shout()"HELLO!"Returns "HELLO!"
7Print outputprintln("HELLO!")HELLO! printed to console
💡 Function call completes and program ends after printing.
Variable Tracker
VariableStartAfter 1After 2Final
wordundefinedundefined"hello""hello"
this (inside shout)N/AN/AN/A"hello"
result (shout output)N/AN/AN/A"HELLO!"
Key Moments - 2 Insights
Why can we call shout() on a String even though String class has no shout() method?
Because shout() is an extension function defined for String, it acts like a new method added externally. See execution_table step 3 where word.shout() calls the extension.
What does 'this' mean inside the extension function?
'this' refers to the object the function is called on. In step 4, 'this' is "hello", so uppercase() works on that string.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the value of 'this' inside shout()?
A"HELLO!"
Bnull
C"hello"
Dword variable
💡 Hint
Check step 4 where this.uppercase() is evaluated on "hello".
At which step does the shout() function return its result?
AStep 5
BStep 6
CStep 3
DStep 7
💡 Hint
Look for the step labeled 'Return from shout()' in the execution_table.
If we changed shout() to add two exclamation marks instead of one, which step would change?
AStep 5
BStep 6
CStep 4
DStep 7
💡 Hint
Step 5 shows adding the exclamation mark to the uppercase string.
Concept Snapshot
Extension function syntax:
fun TypeName.functionName(params) = body
Called like: object.functionName()
Inside, 'this' is the object
Adds new functions without changing original class
Useful for cleaner, readable code
Full Transcript
This visual trace shows how Kotlin extension functions work. First, we define an extension function shout() for String that returns the uppercase version plus an exclamation mark. Then we create a variable word with value "hello". When we call word.shout(), the function runs with 'this' as "hello". It converts to uppercase "HELLO", adds "!", and returns "HELLO!". Finally, println prints the result. Extension functions let us add new behaviors to existing types without modifying their code.

Practice

(1/5)
1. What is the correct way to declare an extension function greet for the String type in Kotlin?
easy
A. extension fun String greet() { println("Hello") }
B. fun greet(String) { println("Hello") }
C. fun String.greet() { println("Hello, $this") }
D. fun greet() String { println("Hello") }

Solution

  1. Step 1: Understand extension function syntax

    Extension functions use the syntax fun ReceiverType.functionName(). Here, String is the receiver type.
  2. Step 2: Match the syntax with options

    fun String.greet() { println("Hello, $this") } correctly uses fun String.greet(). Other options do not follow this syntax.
  3. Final Answer:

    fun String.greet() { println("Hello, $this") } -> Option C
  4. Quick Check:

    Extension function syntax = fun ReceiverType.functionName() [OK]
Hint: Look for 'fun ReceiverType.functionName()' pattern [OK]
Common Mistakes:
  • Using 'extension' keyword which doesn't exist
  • Placing receiver type as function parameter
  • Missing receiver type before function name
2. Which of the following is the correct syntax to declare an extension function square for Int that returns the square of the number?
easy
A. fun Int.square(): Int = this * this
B. fun Int.square() { this * this }
C. fun Int.square() = Int * Int
D. fun square(Int): Int = this * this

Solution

  1. Step 1: Check extension function declaration with return type

    The syntax is fun ReceiverType.functionName(): ReturnType = expression. fun Int.square(): Int = this * this matches this.
  2. Step 2: Verify usage of 'this' and return

    fun Int.square(): Int = this * this correctly uses this * this and returns Int. fun Int.square() { this * this } uses braces (block body) but misses return statement, thus returns Unit. fun Int.square() = Int * Int uses invalid Int * Int.
  3. Final Answer:

    fun Int.square(): Int = this * this -> Option A
  4. Quick Check:

    Extension function with return type = fun ReceiverType.functionName(): Type [OK]
Hint: Remember extension functions use receiver before dot and return type after parentheses [OK]
Common Mistakes:
  • Placing receiver type as function parameter
  • Using braces without return in expression body
  • Incorrect return type placement
3. What will be the output of the following Kotlin code?
fun String.shout() = this.uppercase() + "!"

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

Solution

  1. Step 1: Understand the extension function behavior

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

    Calling word.shout() returns "HELLO!" which is printed.
  3. Final Answer:

    HELLO! -> Option B
  4. Quick Check:

    Extension function output = uppercase + "!" [OK]
Hint: Check what extension function returns and apply to variable [OK]
Common Mistakes:
  • Assuming original string changes
  • Ignoring uppercase conversion
  • Thinking extension functions modify original object
4. Identify the error in the following Kotlin extension function declaration:
fun Int.double {
    return this * 2
}
medium
A. Missing parentheses after function name
B. Cannot use 'this' in extension functions
C. Return statement not allowed in extension functions
D. Extension functions cannot be declared for Int

Solution

  1. Step 1: Check function declaration syntax

    Functions must have parentheses after the name, even if no parameters are present. Here, double misses parentheses.
  2. Step 2: Verify other parts

    Using this is valid in extension functions. Return statements are allowed. Extension functions can be declared for Int.
  3. Final Answer:

    Missing parentheses after function name -> Option A
  4. Quick Check:

    Function declaration requires parentheses () [OK]
Hint: Always add () after function name even if no parameters [OK]
Common Mistakes:
  • Omitting parentheses in function declaration
  • Misunderstanding 'this' usage
  • Thinking return is disallowed
5. You want to add an extension function isEven() to Int? (nullable Int) that returns true if the number is even, and false if it's odd or null. Which is the correct way to declare this extension function?
hard
A. fun Int.isEven(): Boolean = this % 2 == 0 || this == null
B. fun Int.isEven(): Boolean = this % 2 == 0
C. fun Int?.isEven(): Boolean { if (this == null) return false else return this % 2 != 0 }
D. fun Int?.isEven(): Boolean = this != null && this % 2 == 0

Solution

  1. Step 1: Understand nullable receiver type

    To extend nullable Int, use Int? as receiver type. fun Int?.isEven(): Boolean = this != null && this % 2 == 0 does this correctly.
  2. Step 2: Check logic for null and even check

    fun Int?.isEven(): Boolean = this != null && this % 2 == 0 uses concise expression: returns false if null, true if even. fun Int?.isEven(): Boolean { if (this == null) return false else return this % 2 != 0 } is verbose but has incorrect logic (returns true for odd). fun Int.isEven(): Boolean = this % 2 == 0 || this == null incorrectly uses non-nullable receiver and wrong logic. fun Int.isEven(): Boolean = this % 2 == 0 ignores null.
  3. Final Answer:

    fun Int?.isEven(): Boolean = this != null && this % 2 == 0 -> Option D
  4. Quick Check:

    Nullable receiver uses '?' and checks null explicitly [OK]
Hint: Use '?' after type for nullable receiver and check null inside [OK]
Common Mistakes:
  • Not using nullable receiver type for Int?
  • Ignoring null checks inside function
  • Using non-nullable receiver for nullable types
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