I am using scala 2.13. I am trying to create a companion object for a generic class named Point that represents 2D point. Here is the code:
import scala.math.Numeric
class Point[T: Numeric](val x: T, val y: T) {
import scala.math.Numeric.Implicits._
private def getDistance(otherPoint: Point[T]): Double = {
math.sqrt(math.pow((otherPoint.x - x).toDouble, 2) +
math.pow((otherPoint.y - y).toDouble, 2))
}
override def toString = "(" + x + "," + y + ")"
}
object Point[T: Numeric] {
def isWithinDistance(otherPoint: Point[T], distance: Double): Boolean = {
return getDistance(otherPoint) <= distance
}
}
But in the 13th line where I defined a companion object, I gave the type param which is similar to class Point but I get the following error: ';' expected but '[' found. click Here to see the location of the error
How do we create companion objects for generic classes and how do we use the companion object to access methods defined in the class in some other driver program?
You can't parametrize an object, and, more importantly, you don't need to :)
Objects are singletons, and their purpose is capturing things common for the entire type, and independent from the concrete instances (that's why your function also need two Point
parameters, not one).
object Point {
def isWithinDistance[T : Numeric](
point: Point[T],
otherPoint: Point[T],
distance: Double
) = point.getDistance(otherPoint) <= distance
}
As a side note, I don't see any reason for this function to be on the companion object. It should be a regular class method.