我正在尝试使用 Scala 类计算两点之间的距离。但它给出了一个错误说
类型不匹配;找到:other.type(具有基础类型 Point)
required: ?{def x: ?} 请注意,隐式转换不是
适用,因为它们不明确:两种方法any2Ensuring
类型为 [A](x: A)Ensuring[A] 的对象 Predef 和方法 any2ArrowAssoc
在类型 [A](x: A)ArrowAssoc[A] 的对象 Predef 中是可能的
从 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)