0
0
Kotlinprogramming~5 mins

Extensions on built-in types in Kotlin

Choose your learning style9 modes available
Introduction

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.

You want to add a helpful function to a type like String without creating a new class.
You need to reuse a small piece of code that works on built-in types in many places.
You want to make your code more readable by calling functions directly on values.
You want to keep your code organized by grouping related functions with the types they work on.
Syntax
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.

Examples
Adds an exclamation mark to the end of a String.
Kotlin
fun String.addExclamation(): String {
    return this + "!"
}
Checks if an integer is even.
Kotlin
fun Int.isEven(): Boolean {
    return this % 2 == 0
}
Returns the square of a Double using a short syntax.
Kotlin
fun Double.square(): Double = this * this
Sample Program

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.

Kotlin
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()}")
}
OutputSuccess
Important Notes

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.

Summary

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.