I'm trying to calc the distance between two points using a Scala class. But it giving an error saying
type mismatch; found : other.type (with underlying type Point) required: ?{def x: ?} Note that implicit conversions are not applicable because they are ambiguous: both method any2Ensuring in object Predef of type [A](x: A)Ensuring[A] and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A] are possible conversion functions from other.type to ?{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 )
}
}
The following compiles perfectly well for me:
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))
}
I'd also like to point out that your Point
would instead make more sense as a case class:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With