计算点之间的距离
问题描述:
我想使用Scala类来计算两点之间的距离。但它给出错误说计算点之间的距离
类型不匹配;发现:other.type(带底层类型的点) 必需:?{def x:?}请注意,隐式转换不适用于 ,因为它们不明确:两个方法any2在 对象中确保对象Predef类型[A](x:A )确保[A]和方法any2ArrowAssoc 在种类型的目标PREDEF [A](X:A)ArrowAssoc [A]是可能的从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)
}
}
答
以下编写对我来说非常好:
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))
}
我也想指出的是您的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