【问题标题】:Scala trait: How to require output parameter to be Numeric: ambiguous implicit values errorScala trait:如何要求输出参数为数字:模糊隐含值错误
【发布时间】:2017-04-19 03:58:18
【问题描述】:

我正在尝试指定应该返回一些特征的通用函数,如下所示:

import Numeric.Implicits._

trait ReturnsNumberResult {
  def process[T : Numeric](): T
  def output[T : Numeric](v: T)(implicit numeric: Numeric[T]): String
  def runJob(): Any = {
      output(process())
}

当我试图编译这个特征时,我得到了错误:

不明确的隐含值:[错误] 两个对象 BigIntIsIntegral in scala.math.Numeric.BigIntIsIntegral.type 类型的对象数值 [错误] 和对象 IntIsIntegral 在对象 Numeric 类型 scala.math.Numeric.IntIsIntegral.type [错误] 匹配预期类型 数字[T] [错误] 输出(进程())

出了什么问题以及如何实现我的目标?

【问题讨论】:

  • 我相信这个def output[T: Numeric](v: T)(implicit numeric: Numeric[T]) 是多余的。 [T: Numeric] 只是隐式参数声明的语法糖。
  • 谢谢。你是对的

标签: scala


【解决方案1】:

这是由于runJob 没有为您的outputprocess 方法明确声明T: Numeric类型

因此编译器无法在runJob 方法中为outputprocess 方法推断类型T: Numeric

所以你可以像这样修复它:

  def runJob[T: Numeric](): Any = { //explicitly declare the type T: Numeric
    output[T](process()) // In there we explicitly set the type `T` for output, and for `process` method can auto infer from `output` method
  }

【讨论】:

  • 抱歉@chengpohi 我从代码中删除了一个重要部分以简化代码。我现在已经添加了。可以看看吗?
  • @user2975535,更新了答案。希望对你有帮助。
  • 谢谢。你说的对。但我无法更改 runJob 的签名,因为我必须遵循 api。我的特质扩展了 api 特质
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 2011-09-20
  • 2015-05-14
  • 2014-10-09
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多