假设以下特征:
trait A {
type B
def +(a:A):A
}
Run Code Online (Sandbox Code Playgroud)
我使用抽象类型,因为我不想在每次需要A时在类型签名中拖动B.是否仍然可以添加任何隐式证据(使用=:=,<:<等等) +方法,以便编译器仍然可以强制接受a:具有相同B的A?
我的第一直觉是说不,但斯卡拉以前让我惊喜.任何帮助,将不胜感激.
Mil*_*bin 10
无需隐式证据......您可以使用显式细化,
trait A {
self =>
type Self = A { type B = self.B }
type B
def +(a : Self) : Self
}
Run Code Online (Sandbox Code Playgroud)
(注意使用自我类型注释为外部'this'提供别名,允许在Self类型的定义中区分定义和定义的B).
REPL成绩单,
scala> trait A { self => type Self = A { type B = self.B } ; type B ; def +(a : Self) : Self }
defined trait A
scala> val ai = new A { type B = Int ; def +(a : Self) : Self = this }
ai: java.lang.Object with A{type B = Int} = $anon$1@67f797
scala> val ad = new A { type B = Double ; def +(a : Self) : Self = this }
ad: java.lang.Object with A{type B = Double} = $anon$1@7cb66a
scala> ai + ai
res0: ai.Self = $anon$1@67f797
scala> ad + ad
res1: ad.Self = $anon$1@7cb66a
scala> ai + ad
<console>:9: error: type mismatch;
found : ab.type (with underlying type java.lang.Object with A{type B = Double})
required: ai.Self
ai + ab
Run Code Online (Sandbox Code Playgroud)