scala - 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
?
解决方案
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)
}
}
推荐阅读
- java - 通过键从HashMap中获取值
- google-apps-script - 在电子表格中切换工作表时如何触发功能?
- hibernate - netbeans 11.0 版是否有休眠插件?
- r - 使用 dplyr 创建一个通用的描述表
- c++ - C++ => 没有构造函数可以采用源类型,或者构造函数重载决议不明确
- php - 正则表达式匹配不在特定 div 中的标题标签
- javascript - 如何让 magnific popup 与数组一起使用
- python - Keras 中 LSTM 模型训练一个时期中步数的重要性
- php - 使用 date_sunrise() 和 date_sunset() php 计算白天和晚上的时间量
- wordpress - WPForo 插件。登录现在是 wp-adminlogin,我会根据我使用的计算机获得不同的菜单?