【发布时间】:2011-10-14 09:49:28
【问题描述】:
我需要将两个函数作为参数传递给 scala 函数。然后该函数应该评估它们并从它们那里获取一个数字,然后它将在其中进行操作。此数字可以是 Int、Double 或任何其他数字类型。我希望该功能能够正常工作,无论它使用什么类型。
下面的例子解释了这个问题。
import Numeric.Implicits._
class Arithmetic[T : Numeric](val A: Connector[T], val B: Connector[T]) {
val sum = new Connector({ A.value + B.value })
}
class Constant[T](var x: T) {
val value = new Connector({ x })
}
class Connector[T](f: => T) {
def value: T = f
override def toString = value.toString()
}
object Main extends App{
val n1 = new Constant(1)
// works
val n5 = new Constant(5)
val a = new Arithmetic( n1.value, n5.value )
println(a.sum)
// no works
val n55 = new Constant(5.5)
val b = new Arithmetic( n1.value, n55.value )
println(b.sum)
}
我也试过了
class Arithmetic[T,R : Numeric](val A: Connector[T], val B: Connector[R]) {
和其他几种组合,但我最终得到了
error: could not find implicit value for parameter num: scala.math.Numeric[Any]
val sum = new Connector({ A.value + B.value })
【问题讨论】:
标签: generics scala numeric implicit