首页 > 解决方案 > How to represent contravariant type parameter using bounds

问题描述

Here is original trait that can be implemented easily without any problems:

trait ZPar[-KNV,+KV] {
  def get(i: KNV):List[KV]
}

Now I'm trying to emulate variances using bounds (similar to what dotty is doing)

trait ZPar[KNV,KV] {
   def get[R  >: KNV](i: R):List[_<:KV]
}

Looks good so far. Until I'm trying to implement it:

object ZParImp extends ZPar[String,Int]{
  override def get(i: String):List[_<:Int] = {
    val v:String = i
    List(5)
  }
}
//ERROR: method get overrides nothing

Method get cannot be overriden like that.

Is there any way to override method get ?

标签: scalagenericstypes

解决方案


If we provide a type parameter, imitating the original, it seems to work.

object ZParImp extends ZPar[String,Int]{
  override def get[S >: String](i: S):List[_<:Int] = {
    val v :S = "blah"  // <--it's a String
    List(5)
  }
}

推荐阅读