Scala将递归有界类型参数(F-bounded)转换为类型成员

时间:2013-01-09 18:45:10

标签: scala types parametric-polymorphism type-members bounded-quantification

我将如何转换:

trait Foo[A <: Foo[A]]

到类型成员?

即,我想要的内容如下:

trait Foo {
  type A <: Foo {type A = ???}
}

但我遇到了困难,因为名称A已经在类型细化中被采用。这个问题类似(并衍生自):F-bounded quantification through type member instead of type parameter?

1 个答案:

答案 0 :(得分:16)

使用自我类型:

scala> trait Foo { self => type A <: Foo {type A = self.A}}
defined trait Foo

scala> class Bar extends Foo { type A = Bar }
defined class Bar

scala> class Bar extends Foo { type A = Int }
<console>:10: error: overriding type A in trait Foo with bounds <: Foo{type A = Bar.this.A};
 type A has incompatible type
       class Bar extends Foo { type A = Int }
                                    ^