4

我刚刚开始使用 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
4

1 回答 1

1

我不太确定实际上对您施加了哪些约束,例如,哪些类应该/必须是私有的,但是使用 F 有界多态性可能是您想要的解决方案的垫脚石。

/* Simplified interface (adding sqrt is straight-forward) */

abstract class Point[P <: Point[P]] {
  def +(that: P): P
}

/* Two implementations */

class PointInt(val x:Int,val y:Int) extends Point[PointInt] {
  def +(that:PointInt) = new PointInt(this.x + that.x, this.y + that.y)
}

class PointDouble(val x:Double,val y:Double) extends Point[PointDouble] {
  def +(that:PointDouble) = new PointDouble(this.x + that.x, this.y + that.y)
}

/* Companion object */

object Point {
  def apply(x:Int,y:Int) = new PointInt(x,y)
  def apply(x:Double,y:Double) = new PointDouble(x,y)
}

/* Use cases */

val a = Point(1,2)
val b = Point(3,4)
val c = a+b // ok
val d = Point(1.0, 2.5)
val e = c+d // error: type mismatch

但是请注意,如果您想隐藏您的实现,即,将它们设为私有并仅使用泛型声明公共接口,这将无济于事Point- 正如其他人已经指出的那样。

于 2013-06-03T09:56:05.730 回答