Reputation: 26149
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 )
}
}
Upvotes: 4
Views: 4924
Reputation: 61726
You could alternatively use the built-in hypot
function (as in "hypotenuse") from the math
module to compute the distance between two points:
case class Point(x: Double, y: Double)
def distance(a: Point, b: Point): Double =
math.hypot(a.x - b.x, a.y - b.y)
Upvotes: 3
Reputation: 38247
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
Upvotes: 5