generics - 如何指定一个泛型函数,其工作方式就像有 Int、Double 等父类(super class)型一样?

标签 generics math scala

我需要定义一个类来保证基本数字运算的存在(+-*,...)

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/

相关文章:

java - 是什么导致了 java 泛型和反射的编译错误?

scala - Scala Spark 中未调用 RDD 的 Map 函数

scala - 在特征体 Scala 中引用未初始化的值

java - 如何计算特定角度的圆上的位置?

c# - 使用方法 : Find a good mathematical algorithm to distribute measuring points over time?

java - 使用 Apache Commons Math 从数字系列中获取中位数

scala - Scala 中的重载索引运算符

java - 无类型的列表实现

swift - 递归解析 CollectionType

Java泛型二义性方法