实现内部非静态接口
Implement inner non-static interface
我想从包装外部实例化一个内部非静态接口 class。
这可能吗?
考虑以下代码:
shared class AOuterClass() {
Integer val = 3;
shared interface AInterface {
shared Integer val => outer.val;
}
}
void test() {
AOuterClass o = AOuterClass();
object impl satisfies ???.AInterface{}
}
我认为 object impl satisfies o.AInterface{}
是我合理的直觉,但编译器不允许。
像你这样的情况是不可能的。
锡兰规范说 (section 4.5.4 Class Inheritance):
A subclass of a nested class must be a member of the type that declares the nested class or of a subtype of the type that declares the nested class. A class that satisfies a nested interface must be a member of the type that declares the nested interface or of a subtype of the type that declares the nested interface.
因此您只能在声明 class 或其中的子 class 中满足嵌套接口。有类似的语言用于通过新接口扩展嵌套接口。
这并没有直接提到 object
声明,但那些只是 class 定义的快捷方式,稍后在 Anonymous classes:
中详细说明
The following declaration:
shared my object red extends Color('FF0000') {
string => "Red";
}
Is exactly equivalent 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.
所以这也涵盖了 object
个声明。
你可以做什么(我没有测试这个):
AOuterClass.AInterface test(){
object o extends AOuterClass() {
shared object impl satisfies AInterface{}
}
return o.impl;
}
当然,这不适用于现有的 AOuterClass
对象,仅适用于新创建的对象。看到这允许访问对象的私有值,这似乎是一件好事。
我想从包装外部实例化一个内部非静态接口 class。
这可能吗?
考虑以下代码:
shared class AOuterClass() {
Integer val = 3;
shared interface AInterface {
shared Integer val => outer.val;
}
}
void test() {
AOuterClass o = AOuterClass();
object impl satisfies ???.AInterface{}
}
我认为 object impl satisfies o.AInterface{}
是我合理的直觉,但编译器不允许。
像你这样的情况是不可能的。
锡兰规范说 (section 4.5.4 Class Inheritance):
A subclass of a nested class must be a member of the type that declares the nested class or of a subtype of the type that declares the nested class. A class that satisfies a nested interface must be a member of the type that declares the nested interface or of a subtype of the type that declares the nested interface.
因此您只能在声明 class 或其中的子 class 中满足嵌套接口。有类似的语言用于通过新接口扩展嵌套接口。
这并没有直接提到 object
声明,但那些只是 class 定义的快捷方式,稍后在 Anonymous classes:
The following declaration:
shared my object red extends Color('FF0000') { string => "Red"; }
Is exactly equivalent 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.
所以这也涵盖了 object
个声明。
你可以做什么(我没有测试这个):
AOuterClass.AInterface test(){
object o extends AOuterClass() {
shared object impl satisfies AInterface{}
}
return o.impl;
}
当然,这不适用于现有的 AOuterClass
对象,仅适用于新创建的对象。看到这允许访问对象的私有值,这似乎是一件好事。