类型不匹配;找到 point.type,需要 T |斯卡拉

type mismatch; found point.type, required T | Scala

我正在使用 Scala 2.13。我正在尝试将 2d 点定义为 scala class 并创建了一个用于定义函数的伴随对象,如下所示:

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

但是在第 30 行,我写 withinDistanceList.+=(point) 给出了以下错误:

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

click here to see the location of the error

即使类型参数在所有代码中都是统一的,为什么我仍然收到此错误? 谢谢提前。

编译器抱怨,因为你想添加到 Point[T] 类型的 ListBuffer[T] 对象,它说类型 TPoint[T] 不匹配。我假设您想要做的是:

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

ScalaFiddle 示例:https://scalafiddle.io/sf/wDlstcD/0