Junior — Middle
What limitations exist for extension functions in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, extension functions have the following limitations:
- They cannot add new properties or state to classes. Extensions only work with functions.
- Extensions do not modify the actual class, but are statically resolved. This means the call to an extension is determined by the type of the variable at compile time, not the actual runtime type.
- You cannot override existing class methods with extensions. If a method with the same name exists, the class method is called.
- Extensions cannot be declared inside local functions. They must be declared at the file, class, or object level.
Example of static resolution of extensions:
open class Base
class Derived : Base()
fun Base.foo() = "Base"
fun Derived.foo() = "Derived"
fun printFoo(b: Base) {
println(b.foo()) // Will print "Base" because extension is resolved by type Base
}
printFoo(Derived()) // Output: "Base"
This is important to consider when using extension functions in Kotlin.