AnyCompiler

Extension Functions

fun String.shout(): String declares shout() as an extension function on String — a function that can be called as if it were a method on any String, even though String itself wasn't written by you and can't be modified. Inside the function body, this refers to the specific String instance the function was called on.

fun String.shout(): String {
    return this.toUpperCase() + "!"
}

fun main() {
    println("hello".shout())
}
Output
HELLO!

Next: lambdas and higher-order functions — passing behavior itself as a value.

Practice exercise

Write an extension function isEven() on Int that returns whether it's divisible by 2. Print 4.isEven().