Implementation of an internal non-static interface

I would like to instantiate an internal non-static interface from outside the packaging class.

Is it possible?

Consider the following code:

shared class AOuterClass() { Integer val = 3; shared interface AInterface { shared Integer val => outer.val; } } void test() { AOuterClass o = AOuterClass(); object impl satisfies ???.AInterface{} } 

I think that object impl satisfies o.AInterface{} will be my reasonable intuition, but the compiler does not allow this.

+5
source share
1 answer

This is not possible in a case like yours.

The Ceylon specification says ( section 4.5.4 Class Inheritance ):

A subclass of a nested class must be a member of a type that declares a nested class or a subtype of a type that declares a nested class. A class that satisfies a nested interface must be a member of a type that declares a nested interface or a subtype of a type that declares a nested interface.

That way, you can only satisfy the nested interface inside the declaration class or in its subclass. A similar language exists to extend the nested interface using the new interface.

It does not mention object declarations, but it’s just a shortcut to class definitions, as was developed a bit later, in Anonymous classes :

Next announcement:

 shared my object red extends Color('FF0000') { string => "Red"; } 

It corresponds exactly to:

 shared final class \Ired of red extends Color { shared new red extends Color('FF0000') {} string => "Red"; } shared my \Ired red => \Ired.red; 

Where \Ired is the type name assigned by the compiler.

Thus, it also covers object declarations like yours.

What could you do (I have not tested this):

 AOuterClass.AInterface test(){ object o extends AOuterClass() { shared object impl satisfies AInterface{} } return o.impl; } 

Of course, this does not work for an existing AOuterClass object, only for a newly created one. Seeing that this allows you to access the private value of the object, it seems good.

+6
source

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


All Articles