Kotlin has 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 in extension functions?
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 available when extending a class.
So, allowed statically means that the extension function is syntactic sugar for something like this in Java:
public static void ext(A receiver){ System.out.print(receiver.a); }
This explains why protected members are not available. On the other hand, you can use (and even omit) this in extension functions.
So what is the exact scope of the extension functions?
source share