Introduction
Extensions let you add new features to existing code without changing it. This keeps the original code safe and clean.
Extensions let you add new features to existing code without changing it. This keeps the original code safe and clean.
fun ClassName.newFunction() { // code here }
shout to String that makes text uppercase and adds an exclamation.fun String.shout() = this.uppercase() + "!"
sumAll to List<Int> to sum all numbers in the list.fun List<Int>.sumAll() = this.sum()
This program adds a shout function to String. It prints "HELLO!" without changing the original String class.
fun String.shout() = this.uppercase() + "!" fun main() { val greeting = "hello" println(greeting.shout()) }
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.
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.
greet for the String class in Kotlin?fun ClassName.functionName(), so for String: fun String.greet().fun String.shout() = this.uppercase() + "!"
fun main() {
val word = "hello"
println(word.shout())
}shout() converts the string to uppercase and adds an exclamation mark.fun Int.addFive() = this + 5
fun main() {
val number = 10
println(number.addfive())
}addFive() is correctly defined on Int with proper syntax.addfive() with lowercase 'f', which does not match the defined function name.isEven() to the Int class that returns true if the number is even, without modifying the original Int class. Which Kotlin code correctly achieves this and why does it not change the original class?fun Int.isEven() = this % 2 == 0 defines an extension function on Int using fun Int.isEven(), which is the correct way.Pass the test and this pattern moves unknown