2014-10-04 176 views
2

我想使用Scala類來計算兩點之間的距離。但它給出錯誤說計算點之間的距離

類型不匹配;發現:other.type(帶底層類型的點) 必需:?{def x:?}請注意,隱式轉換不適用於 ,因爲它們不明確:兩個方法any2在 對象中確保對象Predef類型[A](x:A )確保[A]和方法any2ArrowAssoc 在種類型的目標PREDEF [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) 
    } 
} 

回答

4

以下編寫對我來說非常好:

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