Extension functions
- Kotlin course
- Intermediate
- Lesson 36/116
- 5 min
Learn extension functions with fun Receiver.ext().
Extension function
An extension function adds a method to an existing type from outside. The declaration puts the receiver type (ReceiverType.) before the function name. The type itself does not change.
Example: fun String.shout(): String { return uppercase() + "!" }. This function adds shout to String. Calling "hi".shout() returns HI!. Extension functions are resolved statically; they do not touch the type's source. This is useful for extending third-party types.
The shout function
Inside an extension function body, this refers to the receiver object. The receiver's own methods can be called directly.
Example: fun String.shout(): String { return uppercase() + "!" }. Here uppercase() actually means this.uppercase(). Calling "hi".shout() returns HI!. Extension functions are used like in-class methods; they do not modify the class source. They are ideal for extending library types.
Practice The String.shout extension
Define an extension function fun String.shout(): String whose body returns uppercase() + "!". In main print the result of "hi".shout() with println.
Starter code
// Define the String.shout extension
// shout returns uppercase plus exclamation
// call it in main and printSample solution
fun String.shout(): String {
return uppercase() + "!"
}
fun main() {
println("hi".shout())
}Expected output
HI!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is an <strong>extension function</strong> declared?
- fun Receiver.method() Correct answer
- function Receiver.method()
- extension Receiver.method()
- class Receiver { method() }
Explanation: An extension function is written as fun Receiver.method().
2 Complete the extension function definition
fun ____.shout(): String {
return uppercase() + "!"
}
fun String.shout(): String {
return uppercase() + "!"
}
Explanation: fun String.shout adds a method to String.
3 Match the extension function parts
| Term | Meaning |
|---|---|
fun String.shout |
Receiver and method |
uppercase() |
Receiver method |
"hi".shout() |
Call |
HI! |
Return value |