scala - 通过隐式类重载泛型方法
问题描述
当我尝试通过隐式类为类创建扩展并重载现有的泛型方法时,它失败并出现编译错误:
error: overloaded method value getAs with alternatives:
(fieldName: String)String <and>
(i: Int)String
cannot be applied to (FooField.type)
r.getAs[String](FooField)
虽然通过隐式重载普通(非泛型)方法可以正常工作。在 Scala 2.12.10 上试过。链接到scastie。我错过了什么?编码:
trait Row {
// Two overloads for `getAs[T]`
def getAs[T](i: Int): T
def getAs[T](fieldName: String): T
// Two overloads for `get`
def get(i: Int): String
def get(fieldName: String): String
}
trait Field {
def columnName: String
def columnDescription: String
}
case object FooField extends Field {
def columnName: String = "Foo"
def columnDescription: String = "Foo desc"
}
object Implicits {
implicit class RowEx(val r: Row) extends AnyVal {
def getAs[T](field: Field): T = r.getAs[T](field.columnName)
def get(field: Field): String = {
println(s"RowEx.get: field")
r.get(field.columnName)
}
}
}
object Main {
import Implicits._
// Create some instance of `Row`
val r = new Row {
def getAs[T](i: Int): T = i.toString.asInstanceOf[T]
def getAs[T](fieldName: String): T = fieldName.toString.asInstanceOf[T]
def get(i: Int): String = i.toString
def get(fieldName: String): String = fieldName
}
def main(args: Array[String]): Unit = {
// Call extension method => `RowEx.get`
println(r.get(FooField))
// Call extension method => `RowEx.get`
// Won't compile with compilation error:
/*
overloaded method value getAs with alternatives:
(fieldName: String)String
(i: Int)String
cannot be applied to (FooField.type)
*/
println(r.getAs[String](FooField))
}
}
解决方案
推荐阅读
- javascript - 当使用带有 {stdio: 'inherit'} 的 child_process.spawn() 方法时,父进程是否可以从子进程接收输出?
- css - 为什么引导表单选择控件看起来有点奇怪?
- javascript - 如何将字符串转换为对象
- android - 如何重新检查简历的权限
- php - 更改 Woocommerce 中显示的变化量
- c# - 不能将泛型类型从类的新实例传递给类方法
- node.js - 节点中的 HTTPS TLS 设置
- javascript - 在反应组件中发出渲染数组而不使用返回
- r - 如何在情节中制作垂直线段?
- unicode - 具有 5 个十六进制值的 Python Unicode 转义序列