Kotlin features a couple of visibility modifiers as well as extension functions. The documentation states that Extensions are resolved statically
. But what does this mean for the visibility of class members within extension functions?
Let's consider the following contrived example:
class A { protected val a = "Foo" }
fun A.ext() { print(a) } //Raises: Cannot access 'a': it is 'protected' in 'A'
class B { val b = "Bar" }
fun B.ext() { print(b) } //Compiles successful
The code will not compile. It seems that protected members are not accessible when extending the class.
So does resolved statically mean the extension function is syntactic sugar for having something like this in Java:
public static void ext(A receiver){ System.out.print(receiver.a); }
This would explain why protected members aren't accessible. On the other hand it's possible to use (and even omit) this
in extension functions.
So what is the exact scope of extension functions?