简体   繁体   中英

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]?

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 :-)

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