0
0
Kotlinprogramming~5 mins

Why extensions add without modifying in Kotlin

Choose your learning style9 modes available
Introduction

Extensions let you add new features to existing code without changing it. This keeps the original code safe and clean.

You want to add a new function to a class from a library you can't change.
You want to keep your code organized by adding helpers outside the main class.
You want to add features to built-in types like String or List.
You want to avoid breaking existing code by not modifying original classes.
Syntax
Kotlin
fun ClassName.newFunction() {
    // code here
}
Extensions look like normal functions but are declared outside the class.
They do not change the original class or its bytecode.
Examples
Adds a new function shout to String that makes text uppercase and adds an exclamation.
Kotlin
fun String.shout() = this.uppercase() + "!"
Adds sumAll to List<Int> to sum all numbers in the list.
Kotlin
fun List<Int>.sumAll() = this.sum()
Sample Program

This program adds a shout function to String. It prints "HELLO!" without changing the original String class.

Kotlin
fun String.shout() = this.uppercase() + "!"

fun main() {
    val greeting = "hello"
    println(greeting.shout())
}
OutputSuccess
Important Notes

Extensions do not actually insert code into the original class; they are static functions called with special syntax.

If the original class has a function with the same name and parameters, the class's function is called instead of the extension.

Summary

Extensions add new functions without changing original code.

This keeps code safe and easy to maintain.

They are useful for adding helpers to classes you don't own.