Junior — Middle
Can an extension function defined inside a class in Kotlin access its fields and methods?
sobes.tech AI
Answer from AI
Extension functions in Kotlin are not true class methods; they are compiled into static functions that take an object as a parameter. Therefore, they do not have direct access to the class's private fields and methods.
However, if an extension function is defined inside a class, it can access the members of that class, but not the private members of the object to which the extension is applied.
Example:
class MyClass {
private val secret = "secret"
fun String.extensionFunction() {
println(this) // access to String
// println(secret) // Error: no access to private field of String object
}
fun test() {
"Hello".extensionFunction() // call to extension function
}
}
Thus, an extension function inside a class can access the members of the class in which it is declared, but not the private fields and methods of the object to which the extension is applied.