如何在 Scala 数字泛型函数中设置默认类型?

问题描述

我的问题很简单。

我已经阅读了一些可能的重复项,例如 Scala: specify a default generic type instead of NothingDefault 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...") 

Working example

当然,您可以像 import B.sum 一样使用 sum 来引用函数。