计算点间距离

Ant*_*yrd 4 scala

我正在尝试使用 Scala 类计算两点之间的距离。但它给出了一个错误说

类型不匹配; 找到:other.type(具有基础类型Point):?{def x: ?} 请注意,隐式转换不适用,因为它们是不明确的:这两种方法 any2Ensuring 在类型为 [A](x: A)Ensuring[ 的对象 Predef 中A] 和类型 [A](x: A)ArrowAssoc[A] 的对象 Predef 中的 any2ArrowAssoc 方法是可能的从 other.type 到 ?{def x: ?} 的转换函数

class Point(x: Double, y: Double) {
  override def toString = "(" + x + "," + y + ")"


  def distance(other: Point): Double = {
    sqrt((this.x - other.x)^2 + (this.y-other.y)^2 )
  }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*lun 5

以下对我来说编译得很好:

import math.{ sqrt, pow }

class Point(val x: Double, val y: Double) {
  override def toString = s"($x,$y)"

  def distance(other: Point): Double =
    sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
}
Run Code Online (Sandbox Code Playgroud)

我还想指出,您Point作为案例类会更有意义:

case class Point(x: Double, y: Double) { // `val` not needed
  def distance(other: Point): Double =
    sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
}

val pt1 = Point(1.1, 2.2) // no 'new' needed
println(pt1)  // prints Point(1.1,2,2); toString is auto-generated
val pt2 = Point(1.1, 2.2)
println(pt1 == pt2) // == comes free
pt1.copy(y = 9.9) // returns a new and altered copy of pt1 without modifying pt1
Run Code Online (Sandbox Code Playgroud)