我需要定义一个类来保证基本数字运算的存在(+
、-
、*
,...)
def Arithmetic[T <: AnyVal](a: T, b: T) {
val x = a + b
}
AnyVal
未定义 +
。第二次尝试:
import Numeric.implicits._
def Arithmetic[T <% Numeric](a: T, b: T) {
val x = a + b
}
到目前为止一切顺利,但现在我强制 T
具有相同的类型。因此,Arithmetic(double, int)
将失败。我真正的应用程序更加人为:
class Arithmetic[T](A: Connector[T], B: Connector[U])(implicit n: Numeric[T]) {
val sum = new Connector({ n.plus(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 )
// doesn't work
val n55 = new Constant(5.5)
val b = new Arithmetic( n1.value, n55.value )
}
想法?建议?我只需要一些东西来保证我能够在该类中进行基本的数学运算......
最佳答案
认为你应该使用context bounds这里
def arithmetic[T: Numeric](a: T, b: T) = {
import Numeric.Implicits._
a + b
}
它有效,至少对于 scala 2.9.1
scala> arithmetic(1, 2.2)
res0: Double = 3.2
关于generics - 如何指定一个泛型函数,其工作方式就像有 Int、Double 等父类(super class)型一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7766256/