[英]Scala generics and type mismatch
the following code errors with a 'type mismatch' error, saying that FooProcessor should be Processor[M]. 以下代码错误带有“类型不匹配”错误,表示FooProcessor应该为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]? 如何使编译器相信FooProcessor是Processor [Model]的扩展?
The short answer is that your FooProcessor
is an extension of Processor[Foo]
, and is specific to Foo
. 简短的答案是,您的FooProcessor
是Processor[Foo]
的扩展,并且特定于Foo
。 In DelegatingProcessor
, you need a Processor
that is able to handle not only Foo
, but any valid Model
. 在DelegatingProcessor
,您需要一个不仅能够处理Foo
而且能够处理任何有效Model
的Processor
。 FooProcessor
simply doesn't fit the bill here. FooProcessor
根本不适合这里的账单。 And — don't try to convince the compiler otherwise, because the compiler is here exactly to prevent this kind of mistakes :-) 并且-不要试图说服编译器,因为编译器正是在这里防止这种错误:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.