Tutankhamen
Tutankhamen

Reputation: 3562

Generics in SCALA

I have a simple generic class in 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!

Upvotes: 1

Views: 111

Answers (1)

Tutankhamen
Tutankhamen

Reputation: 3562

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)
}

Upvotes: 2

Related Questions