【发布时间】:2020-12-29 18:53:51
【问题描述】:
我的问题很简单。
我已经阅读了一些可能的重复内容,例如 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 一样
如果您能给我任何提示,我真的很感激。
【问题讨论】:
-
声明一个默认值怎么样?
def sum[T](name: String)(implicit numeric: Numeric[T] = Numeric[Double]) -
@Jatin 谢谢,我试过了。但我得到了错误:scala.math.Numeric.type 类型的值 Numeric 不采用类型参数。斯卡拉版本:2.11.12
-
评论中的上述行完美编译。
-
@Jatin 是的,它可以编译,但是当我执行该方法时出现错误。 / def sum[T](name: String)(隐式数字: Numeric[T] = Numeric[Double]): String = {"hello world!"} / sum("abc") => 错误:模糊的隐式值
标签: scala generics generic-programming