【问题标题】:How to set default type in Scala Numeric Generic Function?如何在 Scala 数值泛型函数中设置默认类型?
【发布时间】:2020-12-29 18:53:51
【问题描述】:

我的问题很简单。

我已经阅读了一些可能的重复内容,例如 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 一样

如果您能给我任何提示,我真的很感激。

【问题讨论】:

  • 声明一个默认值怎么样? 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


【解决方案1】:

对于这种情况,你可以使用这个技巧:

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一样。

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2017-06-20
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    相关资源
    最近更新 更多