我刚刚开始使用 Scala,并且正在编写一些教程。我遇到了伴随对象,并将它们用作工厂。我尝试了几件事。但是,我没有让以下内容正常工作。无法理解它。
import math._
abstract class Point{
// ...
}
object Point{
private class PointInt(val x:Int,val y:Int) extends Point{
def +(that:PointInt) = new PointInt(this.x + that.x, this.y + that.y)
def distance(that:PointInt) =
sqrt(pow((this.x - that.x), 2) + pow((this.y - that.y), 2))
}
private class PointDouble(val x:Double,val y:Double) extends Point{
def +(that:PointDouble) = new PointDouble(this.x + that.x, this.y + that.y)
def distance(that:PointDouble) =
sqrt(pow((this.x - that.x), 2) + pow((this.y - that.y), 2))
}
def apply(x:Int,y:Int):Point = new PointInt(x,y)
def apply(x:Double,y:Double):Point = new PointDouble(x,y)
}
val a = Point(1,2)
val b = Point(3,4)
val c = a+b // does not work...
只是想把两个整数点相加,就像我在方法中定义的那样......有谁知道我做错了什么?
编辑:我试图将以下(工作)类包装在工厂中。
class Point(val x:Int,val y:Int){
def +(that:Point) = new Point(this.x + that.x, this.y + that.y)
def distance(that:Point) = sqrt(pow((this.x - that.x),2) + pow((this.y - that.y),2))
}
val a = new Point(1,2) //> a : week1.OU2.Point = week1.OU2$Point@73e48fa7
val b = new Point(3,4) //> b : week1.OU2.Point = week1.OU2$Point@677bb8fe
val c = a+b //> c : week1.OU2.Point = week1.OU2$Point@6bae60c5
c.x //> res0: Int = 4
c.y //> res1: Int = 6