问题描述
我的问题很简单。
我已经阅读了一些可能的重复项,例如 Scala: specify a default generic type instead of Nothing、Default generic type on method in scala
但这些情况和我的不一样。
// define
def sum[T](name: String)(implicit numeric: Numeric[T]): ...
def sum(name: String) = sum[Double](name)
// use
val a = sum[Long]("name...") // It's OK.
val b = sum("name...") // ERROR: ambiguous reference to overloaded deFinition
我想使用 sum("....") 与 sumDouble 相同
如果您能给我任何提示,我真的很感激。
解决方法
对于这种情况,您可以使用此技巧:
trait A {
def sum[T](name: String)(implicit numeric: Numeric[T]): String = numeric.zero.toString
}
object B extends A {
def sum(name: String): String = sum[Double](name)
}
// use
val a = B.sum[Long]("name...")
val b = B.sum("name...")
当然,您可以像 import B.sum
一样使用 sum
来引用函数。