[英]Generics in SCALA
I have a simple generic class in SCALA: 我在SCALA中有一个简单的泛型类:
class Point[T : Numeric](val x:T, val y:T) {
def + (other : Point[T]) : Point[T] = new Point[T] ( x + other.x, y + other.y)
def - (other : Point[T]) : Point[T] = new Point[T] ( this.x - other.x, this.y - other.y)
def unary_ : Point[T] = new Point[T](-this.x, -this.y)
def == (other : Point[T]) : Boolean = (this.x == other.x && this.y == other.y)
def != (other : Point[T]) : Boolean = !(this == other)
}
but I'm getting this error: 但我收到此错误:
Error:(4, 66) type mismatch;
found : T
required: String
def + (other : Point[T]) : Point[T] = new Point[T] ( x + other.x, y + other.y)
^
what is wrong with my generic? 我的仿制药有什么问题?
Thank you! 谢谢!
Problem was solved like this: 问题是这样解决的:
class Point[T : Numeric](val x:T, val y:T) {
def + (other : Point[T]) : Point[T] = new Point[T] ( plus(this.x, other.x), plus(this.y, other.y))
def - (other : Point[T]) : Point[T] = new Point[T] ( minus(this.x, other.x), minus(this.y, other.y))
def unary_- : Point[T] = new Point[T](negate(this.x), negate(this.y))
def == (other : Point[T]) : Boolean = (this.x == other.x && this.y == other.y)
def != (other : Point[T]) : Boolean = !(this == other)
private val numeric = implicitly[Numeric[T]]
private def plus(x: T, y: T) = numeric plus (x, y)
private def minus(x: T, y: T) = numeric minus (x, y)
private def negate(x: T) = numeric negate (x)
}
So, I just use Numeric interface implicitly... Let's make it even simpler: 所以,我只是隐式地使用数字接口...让我们变得更加简单:
import scala.math.Fractional
class Point[T](val x: T, val y: T)(implicit num: Fractional[T]) {
import num.mkNumericOps
def +(that: Point[T]) = new Point(this.x + that.x, this.y + that.y)
def -(that: Point[T]) = new Point(this.x - that.y, this.y - that.y)
def == (other : Point[T]) : Boolean = (this.x == other.x && this.y == other.y)
def != (other : Point[T]) : Boolean = !(this == other)
def unary_- : Point[T] = new Point[T](-this.x, -this.y)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.