Protected members not available in extension features?

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?

+5
source share
1 answer

You are right, extension functions / properties are compiled into JVM static methods. As a rule, they are in another class in some other package than the class that they extend, so it is impossible to call the protected methods of this class due to the rules of accessibility of the virtual machine. This is also consistent with the visibility of the protected definition (apparently in the class and its subclasses): the extension function is not a subclass, and it is not defined in the subclass of the class you are extending.

The fact that you can use or skip this in the body of the extension function is only a syntax function, the compiler issues the necessary instructions to load the first parameter of the JVM method.

+6
source

Source: https://habr.com/ru/post/1236541/


All Articles