Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation Distance Between Points

Tags:

scala

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 )
  }
}
like image 325
Antarr Byrd Avatar asked Feb 11 '23 21:02

Antarr Byrd


1 Answers

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
like image 53
Erik Kaplun Avatar answered Feb 19 '23 20:02

Erik Kaplun