【问题标题】:type mismatch; found point.type, required T | Scala类型不匹配;找到 point.type,需要 T |斯卡拉
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-26
      • 2019-04-30
      • 2019-08-22
      • 2016-05-08
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多