如何指定一个泛型函数,其工作方式就像存在 Int、Double 等超类型一样?
数字运算的存在(+
、-
、*
、...)
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 )
}
想法?建议?我只需要一些东西来保证我能够在课堂上进行基本的数学运算......
I need to define a class that guarantees the basic numeric operations will be present (+
, -
, *
, ...)
def Arithmetic[T <: AnyVal](a: T, b: T) {
val x = a + b
}
AnyVal
does not define +
. Second attempt:
import Numeric.implicits._
def Arithmetic[T <% Numeric](a: T, b: T) {
val x = a + b
}
So far so good, but now I am forcing T
to be of the same type. Hence Arithmetic(double, int)
will fail. My real application is even a little more contrived:
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()
}
Now for the usage:
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 )
}
Thoughts? Suggestions? I just need something that guarantees I am able do basic math operations inside that class...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
认为你应该使用 上下文边界 在这里
它可以工作,至少对于 <代码>scala 2.9.1
Think you should use context bounds here
it works, at least for
scala 2.9.1
这是一个想法:
用法:
Here's an idea:
Usage:
这样的事情对你有用吗?
Would something like this work for you?