Alex Mattenet
Alex Mattenet

Reputation: 23

Inference of traits in scala

I'm having trouble with type inference in scala. I'm using classes with higher-kinded types, which extend some traits; but the scala compiler can't resolve the types to the traits they extend. The minimal example is shown here:

trait traitA[X]
trait traitB[X]
class A[X] extends traitA[X] {}
class B extends traitB[C] {}
class C {}

val a = Seq[A[B]]()
val b: Seq[traitA[traitB[C]]] = a

Error: type mismatch;
  found   : Seq[A[B]]
  required: Seq[traitA[traitB[C]]]
    val b: Seq[traitA[traitB[C]]] = a

I can get a Seq[traitA[B]] but not a Seq[traitA[traitB[C]]].

What am I missing here?

Thanks for the help

Upvotes: 2

Views: 56

Answers (1)

nicodp
nicodp

Reputation: 2392

You have to ask for covariance in traitA as follows:

trait traitA[+X]

And you'll get:

scala> val b: Seq[traitA[traitB[C]]] = a
res0: Seq[traitA[traitB[C]]] = List()

Why? because A[X] is a subtype of traitA[X] and you want to enforce that Seq[A[X]] is also a subtype of Seq[traitA[X]].

Upvotes: 2

Related Questions