像在Java中使用内部接口一样,在Scala中实现内部特征 [英] Implementing inner traits in Scala like we do with inner interfaces in Java
问题描述
此Java代码可以正确编译:
This code in Java compiles without errors:
interface T {
interface Q {
}
}
class C implements T.Q {
}
Scala中的此代码不:
whereas this code in Scala does not:
trait T {
trait Q {
}
}
class C extends T.Q {
}
将Java代码列表正确转换为Scala的正确翻译(如果存在)?
What is the correct translation (if it exists) of the Java code listing into Scala?
欢迎对语言设计进行理论解释.
Theoretical explanations about language design are welcome.
推荐答案
内部类型Q
仅为T
特征的特定实例实现定义.由于scala具有与路径相关的类型,因此T
的每个实例都将具有自己的子特性Q
.
The inner type Q
is defined only for specific instance implementation of the T
trait. Since scala has path-dependent types, each instance of T
will have his own subtrait Q
.
scala> trait T {
| trait Q
| }
defined trait T
scala> class C extends T {
| def getQ: this.Q = new this.Q {}
| }
defined class C
scala> val inC = (new C).getQ
inC: C#Q = C$$anon$1@3f53073a
scala> val c = new C
c: C = C@1a7e4ff0
scala> new c.Q {}
res4: c.Q = $anon$1@36bbb2f5
如果您需要一个接口来实现客户端的一般行为,并且不依赖于特定的C
实例,则应在Object
If you need an interface for a generic behavior for your clients to implement, and not dependent on a specific C
instance, you should define it within an Object
scala> object T {
| trait Q {
| def implementMe: Unit
| }
| }
defined module T
scala> val inT = new T.Q {
| def implementMe = println("implemented!")
| }
inT: T.Q = $anon$1@20f2a08b
scala> inT.implementMe
implemented!
为什么要依赖路径类型?
由于设计原因,请在此处
这篇关于像在Java中使用内部接口一样,在Scala中实现内部特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!