简体   繁体   中英

How to solve Scala compiler's “class X inherits different type instances of class Y[Z]” error?

Given the following code:

sealed abstract class Foobar[+Parent <: Foobar[Parent]](parent: Option[Parent])

trait Foo[+Parent <: Foobar[Parent]] extends Foobar[Foo[Parent]]

trait Bar[+Parent <: Foobar[Parent]] extends Foobar[Bar[Parent]]

class Raboof[+Parent <: Foobar[Parent]](val parent: Foo[Parent]) extends Foobar(Some(parent)) with Foo[Parent] with Bar[Parent]

How to solve this inheritance issue in Scala's type system?

Motivation: The hypothetical traits Foo and Bar would implement methods that shall be provided by several classes such as the class Raboof mixing in these traits.

The Scala Worksheet of Scala-SDK Version 3.0.2-vfinal-20131028-1923-Typesafe complains about the following:

illegal inheritance;  class Raboof inherits different type instances of class Foobar: scrap.Foobar[scrap.Bar[Parent]] and scrap.Foobar[scrap.Foo[Parent]]

The different type instances scrap.Foobar[scrap.Bar[Parent]] and scrap.Foobar[scrap.Foo[Parent]] should dissolve into a single type. In my understanding into scrap.Foobar[scrap.Raboof[Parent]] because the class Raboof is mixing in both the traits Foo and Bar .

This definition works:

class Raboof[+Parent <: Foobar[Parent]](val parent: Raboof[Parent]) extends 
  Foobar[Raboof[Parent]](Some(parent)) with Foo[Parent] with Bar[Parent]

Your original definition:

  1. doesn't tell Scala how to combine Foobar[Foo[Parent]] and Foobar[Bar[Parent]] . Since Foobar[Raboof[Parent]] is a subtype of both, this works.

  2. Has the wrong type for val parent , since Foobar[Bar[Parent]] requires parent: Bar[Parent]] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM