Scala type parameter bound error in subclass but n

2019-08-12 08:26发布

问题:

Why don't the following work?

scala> class Foo[B<:Foo[B]]
defined class Foo

scala> class Goo[B<:Foo[B]](x: B)
defined class Goo

scala> class Hoo[B<:Hoo[B]] extends Foo[Hoo[B]] { def f = new Goo(this) }
defined class Hoo

scala> class Ioo extends Hoo[Ioo] { def g = new Goo(this) }
<console>:11: error: inferred type arguments [Ioo] do not conform to class Goo's type parameter bounds [B <: Foo[B]]
       class Ioo extends Hoo[Ioo] { def g = new Goo(this) }
                                            ^

scala> class Ioo extends Hoo[Ioo] { f } // yet this works!
defined class Ioo

回答1:

this in new Goo(this) must be B <: Foo[B]. It is Ioo, so we need Ioo <: Foo[Ioo].

Ioo is Hoo[Ioo], hence Foo[Hoo[Ioo]] (inheritance of Hoo), which does not give a Foo[Ioo].



标签: scala