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


我将如何转换:

trait Foo[A <: Foo[A]]

一个类型的成员?

即,我想要的内容如下:

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

但我遇到了困难,因为名称A已经在类型细化中被采用。这个问题类似(并衍生自): 通过类型成员而不是类型参数进行F-限制量化?


7207
2018-01-09 18:45


起源



答案:


使用自我类型:

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 }
                                    ^

16
2018-01-09 19:56



这是我原来的直觉,很棒的答案! - Alex DiCarlo


答案:


使用自我类型:

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 }
                                    ^

16
2018-01-09 19:56



这是我原来的直觉,很棒的答案! - Alex DiCarlo