Junior — Middle
How does Kotlin determine which class an extension function applies to at runtime?
sobes.tech AI
Answer from AI
In Kotlin, extension functions are static by nature. This means that at runtime, the class of the object on which the function is called is determined based on the static type of the variable, not the actual type of the object. In other words, an extension function is not virtual and cannot be overridden.
Example:
open class Base
class Derived : Base()
fun Base.foo() = "Base"
fun Derived.foo() = "Derived"
fun main() {
val b: Base = Derived()
println(b.foo()) // Will print "Base", despite the object being of type Derived
}
Here, the call to the extension function is determined by the type of the variable b (Base), not the actual type of the object (Derived).