scala - 通用类的伴随对象 | 斯卡拉
问题描述
我正在使用 scala 2.13。我正在尝试为一个名为 Point 的泛型类创建一个伴随对象,该类表示 2D 点。这是代码:
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
}
}
但是在我定义伴随对象的第 13 行中,我给出了类似于类 Point 的类型参数,但我收到以下错误: ';' 预期但找到了“[”。 点击这里查看错误的位置
我们如何为泛型类创建伴生对象,以及如何使用伴生对象访问其他驱动程序中类中定义的方法?
解决方案
你不能参数化一个对象,更重要的是,你不需要:)对象是单例,它们的目的是捕获整个类型的共同点,并且独立于具体实例(这就是为什么你的函数也需要两个 Point
参数,不是一个)。
object Point {
def isWithinDistance[T : Numeric](
point: Point[T],
otherPoint: Point[T],
distance: Double
) = point.getDistance(otherPoint) <= distance
}
作为旁注,我看不出有任何理由将此函数放在伴随对象上。它应该是一个常规的类方法。
推荐阅读
- angular - 配置时刻自定义日期适配器
- c# - 异步调用定时器
- javascript - 如何在节点 js 中使用 moment.js 根据当前日期生成一年的季度数和年份数的数组?
- android - 应用程序突然重启
- python - 散景散点图未显示
- java - Spring boot - Logback - 在所有应用程序日志中记录公共值
- vb.net - Case 中的可编辑值(基于 Vb 的 Ilogic)
- mongodb - 如何将 sum 与 Mongodb 聚合一起使用
- python - 我如何让 python 在文件中查找范围?
- android-studio - 如何为 Calenderview 设置自定义字体?