Scala特性:如何要求输出参数为数字:不明确的隐式值错误
我试图指定泛型函数,该函数应该在trait中返回一些数字,如下所示:Scala特性:如何要求输出参数为数字:不明确的隐式值错误,scala,Scala,我试图指定泛型函数,该函数应该在trait中返回一些数字,如下所示: 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()) } 当我试图编译
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.biginistingegral.type类型的对象数值
[错误]和对象初始化集成在数值类型的对象中
scala.math.Numeric.IntIsIntegral.type[错误]与预期类型匹配
数字[T][error]输出(进程())
错在哪里?如何实现我的目标 这是因为在
runJob
中没有明确声明t:Numeric
的类型以用于输出和处理方法
因此,编译器无法推断runJob
方法中的output
和process
方法的类型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
}
这是由于在runJob
中没有为output
和process
方法显式声明t:Numeric
的类型造成的
因此,编译器无法推断runJob
方法中的output
和process
方法的类型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。我的trait扩展api traitSorry@chengpohi我从代码中删除了一个重要部分,以简化代码。我现在已经添加了它。你能看一下吗?@user2975535,更新了答案。希望对你有帮助。谢谢。你是对的。但我不能更改runJob的签名,因为我必须遵循api。我的特性扩展了api,我相信这def输出[T:Numeric](v:T)(隐式Numeric:Numeric[T])
是多余的<代码>[T:Numeric]
只是隐式参数声明的语法糖。谢谢。你是对的,我相信这个def输出[T:Numeric](v:T)(隐式Numeric:Numeric[T])
是多余的<代码>[T:Numeric]
只是隐式参数声明的语法糖。谢谢。你是对的