【发布时间】:2021-06-14 13:10:31
【问题描述】:
我正在使用 scala 2.13。我正在尝试将 2d 点定义为 scala 类,并创建了一个用于定义函数的伴随对象,如下所示:
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) 的地方出现以下错误:
类型不匹配;找到:point.type(底层类型为 scalalearnings.chapter1.straightforward.Point[T]) 需要:T
click here to see the location of the error
即使类型参数在所有代码中都是统一的,为什么我仍然收到此错误? 提前谢谢。
【问题讨论】:
标签: scala generics companion-object