[英]Scala: type mismatch when calling a method from generic trait
Let's look at some code first: 让我们先来看一些代码:
trait Foo[T] {
def fooize(value : T) : Unit
}
object TestFoo {
def testFooForType[T[_] <: Foo[_]](obj : T[Int]) {
obj.fooize(5)
}
}
Why doesn't it typecheck and how can I overcome this difficulty? 为什么不进行类型检查,如何克服这个困难? What I want to do is to test any class that implements the given trait
Foo
for a particular type T
( Int
in the example). 我想要做的是测试针对特定类型
T
(在示例中为Int
)实现给定特征Foo
任何类。
T[_] <: Foo[_]
means "T forSome type" extends "Foo forSome type". T[_] <: Foo[_]
表示“ T forSome类型”扩展了“ Foo forSome类型”。
It has to allow for cases where the types are different. 它必须允许类型不同的情况。 (T[A] extends Foo[B])
(T [A]扩展为Foo [B])
Binding T with Int type has no effect on Foo's type, which is still unbounded. 将T与Int类型绑定不会影响Foo的类型,Foo的类型仍然不受限制。
You can either specify Foo's type: 您可以指定Foo的类型:
def testFooForType[T[_] <: Foo[Int]](obj : T[_]) {
obj.fooize(5)
}
or you can make the type relationship explicit: 或者您可以使类型关系明确:
def testFooForType[T[V] <: Foo[V]](obj : T[Int]) {
obj.fooize(5)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.