【发布时间】:2014-04-23 16:22:51
【问题描述】:
我的项目中有一个令人困惑的问题,无法完全解决,所以请帮助我!
这是一个简化我原来的示例代码:
trait Sample[A] {
def doit(param: A)
}
case object SampleEx1 extends Sample[Int] {
def doit(param: Int) = {
param + 0
}
}
现在我需要出于外部原因使 A 协方差,但它会导致注释掉的错误:
trait Sample[+A] {
def doit(param: A) // ERR: covariant type A occurs in contravariant position in type A of value param
}
case object SampleEx1 extends Sample[Int] {
def doit(param: Int) = {
param + 0
}
}
所以我 stacoverflowed 并找到了另一种类型 B 的解决方案,但随后又发生了另一个错误:
trait Sample[+A] {
def doit[B >: A](param: B)
}
case object SampleEx1 extends Sample[Int] {
def doit[Int](param: Int) = {
param + 0 // type mismatch; found : Int(0) required: String
}
}
显然param 不再是Int 因为[B >: Int]。
我尝试用自己和谷歌解决这个问题,但无法解决。有人可以帮忙吗?非常感谢! :))
【问题讨论】:
标签: scala covariance contravariance