首页 > 解决方案 > 通用类的伴随对象 | 斯卡拉

问题描述

我正在使用 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 的类型参数,但我收到以下错误: ';' 预期但找到了“[”。 点击这里查看错误的位置

我们如何为泛型类创建伴生对象,以及如何使用伴生对象访问其他驱动程序中类中定义的方法?

标签: scalagenericscompanion-object

解决方案


你不能参数化一个对象,更重要的是,你不需要:)对象是单例,它们的目的是捕获整个类型的共同点,并且独立于具体实例(这就是为什么你的函数也需要两个 Point参数,不是一个)。

    object Point { 
        def isWithinDistance[T : Numeric](
          point: Point[T], 
          otherPoint: Point[T], 
          distance: Double
        ) = point.getDistance(otherPoint) <= distance
    }

作为旁注,我看不出有任何理由将此函数放在伴随对象上。它应该是一个常规的类方法。


推荐阅读