Ben Smith
Ben Smith

Reputation: 1594

Scala generics and type mismatch

the following code errors with a 'type mismatch' error, saying that FooProcessor should be Processor[M].

sealed trait Model
case class Foo extends Model
trait Processor[M <: Model]

class FooProcessor extends Processor[Foo]

class DelegatingProcessor[M <: Model] extends Processor[M] {
  val delegates = Map[String, Processor[M]]("foo" -> new FooProcessor())
}

How to you convince the compiler that FooProcessor is an extension of Processor[Model]?

Upvotes: 1

Views: 336

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

The short answer is that your FooProcessor is an extension of Processor[Foo], and is specific to Foo. In DelegatingProcessor, you need a Processor that is able to handle not only Foo, but any valid Model. FooProcessor simply doesn't fit the bill here. And — don't try to convince the compiler otherwise, because the compiler is here exactly to prevent this kind of mistakes :-)

Upvotes: 3

Related Questions