Introduction
Sometimes you add new functions to existing classes without changing them. Kotlin lets you do this with extensions. But if a class already has a function with the same name, Kotlin uses the class's own function first.
fun ClassName.extensionFunction() { // code here } // Member function inside the class class ClassName { fun memberFunction() { // code here } }
class Example { fun greet() = "Hello from member" } fun Example.greet() = "Hello from extension" fun main() { val e = Example() println(e.greet()) }
class Example { // No greet function here } fun Example.greet() = "Hello from extension" fun main() { val e = Example() println(e.greet()) }
class Person(val name: String) { fun sayHello() = "Hello from member: $name" } fun Person.sayHello() = "Hello from extension: $name" fun main() { val p = Person("Alice") println(p.sayHello()) }
greet for class Person in Kotlin?fun ClassName.functionName().fun Person.greet().class Box {
fun size() = "Member size"
}
fun Box.size() = "Extension size"
fun main() {
val box = Box()
println(box.size())
}size() returning "Member size". An extension function with the same name returns "Extension size".box.size() calls the member function.class Gadget {
fun info() = "Member info"
}
fun Gadget.info() = "Extension info"
fun main() {
val g: Gadget? = null
println(g?.info())
}g is null. The safe call operator ?. prevents calling functions on null.g is null, g?.info() returns null without calling any function.describe() function to class Device without modifying its source code. The class already has a member function describe(). How can you call the extension describe() function explicitly in Kotlin?Pass the test and this pattern moves unknown