0
votes

I am using scala 2.13. I am trying to define a 2d point as a scala class and created one companion object for defining a function as belows:

package scalalearnings.chapter1.straightforward

import scala.math.Numeric
import scala.collection.mutable.ListBuffer

class Point[T: Numeric](val x: T, val y: T) {
  import scala.math.Numeric.Implicits._

  def getDistance(otherPoint: Point[T]): Double = {
    math.sqrt(math.pow((otherPoint.x - x).toDouble, 2) +
      math.pow((otherPoint.y - y).toDouble, 2))
  }

  def isWithinDistance(otherPoint: Point[T], distance: Double): Boolean = {
    if (math.abs((otherPoint.x - x).toDouble()) > distance || math.abs((otherPoint.y - y).toDouble()) > distance)
      false
    getDistance(otherPoint) <= distance
  }

  override def toString = "(" + x + "," + y + ")"
}

object Point {
  import scala.math.Numeric.Implicits._

  def getPointsWithinDistance[T: Numeric](list: ListBuffer[Point[T]], point: Point[T], distance: Double) = {
    val withinDistanceList = ListBuffer[T]()
    for (point <- list) {
      if (point.isWithinDistance(point, distance))
        withinDistanceList.+=(point)
    }

    withinDistanceList.foreach(println)
  }
}

But in line 30, where I wrote withinDistanceList.+=(point) is giving the following error:

type mismatch; found : point.type (with underlying type scalalearnings.chapter1.straightforward.Point[T]) required: T

click here to see the location of the error

Even though the type param is uniform across all the code, why am I still receiving this error? Thanks is advance.

1

1 Answers

0
votes

Compiler complains, because you want add to ListBuffer[T] object of type Point[T] and it says that types T and Point[T] mismatch. I assume what you want to do is something like:

withinDistanceList += point.x
withinDistanceList += point.y

ScalaFiddle example: https://scalafiddle.io/sf/wDlstcD/0