我正在尝试使用Scala类计算两点之间的距离 . 但它给出了一个错误说法
类型不匹配; found:other.type(带底层类型Point)必需:?{def x:?}请注意,隐式转换不适用,因为它们不明确:两个方法any2在对象Predef中设置[A]类型(x:A)确保[对象Predef中的A]和方法any2ArrowAssoc类型[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 )
}
}
2 回答
以下编译非常适合我:
我还想指出,作为一个案例类,你的
Point
会更有意义:您也可以使用
math
模块中的内置hypot函数(如"hypotenuse"中)来计算两点之间的距离: