Extensions let you add new functions to existing types like String or Int without changing their code. This helps you write cleaner and easier-to-read programs.
Extensions on built-in types in Kotlin
fun TypeName.newFunctionName(params): ReturnType { // function body }
Replace TypeName with the built-in type you want to extend, like String or Int.
The function can be called directly on any value of that type.
fun String.addExclamation(): String { return this + "!" }
fun Int.isEven(): Boolean { return this % 2 == 0 }
fun Double.square(): Double = this * this
This program adds two extension functions: one to make a string uppercase and add an exclamation, and one to check if an integer is positive. It then uses them and prints the results.
fun String.shout(): String { return this.uppercase() + "!" } fun Int.isPositive(): Boolean { return this > 0 } fun main() { val word = "hello" println(word.shout()) val number = 10 println("Is $number positive? ${number.isPositive()}") }
Extension functions do not actually change the original class; they are just a convenient way to call new functions on existing types.
You can add extension properties, but they do not store data in the instance (they use getters/setters).
If a member function and an extension function have the same signature, the member function is called.
Extensions let you add new functions to built-in types without changing their code.
They make your code cleaner and easier to read by calling functions directly on values.
Use the syntax fun TypeName.functionName() to create an extension function.