Sobes.tech
Junior — Middle

Is it possible to access private class methods inside an extension function in Kotlin or another programming language?

sobes.tech AI

Answer from AI

In Kotlin, extension functions do not have access to private methods or properties of the class they are applied to. This is because extensions do not modify the class itself; they are static functions with call syntax similar to methods.

Example:

class MyClass {
    private fun privateMethod() = "Private method"
}

fun MyClass.extensionFunction() {
    // this.privateMethod() // Error: cannot access private method
}

If you need to use private methods inside an extension, it is not directly possible. Alternatives:

  • Make the method protected or internal, if acceptable.
  • Add a public or internal wrapper method in the class.
  • Use inheritance and overriding.

In other languages, the situation may differ, but usually private methods are only accessible within the class, and extensions or external functions are not.