2013-06-02 2 views
4

저는 스칼라에서 시작하여 일부 자습서를 작성하고 있습니다. 나는 동반자 물체를 발견하고 그것들을 공장으로 사용했다. 나는 여러 가지 것을 시도했다. 그러나 나는 제대로 작동하기 위해 다음을 얻지 못할 것이다. 캔트 내가 ... 사람이 내가 뭘 잘못 알고 있습니까 방법에 정의처럼 스칼라의 팩터 리 객체입니다.

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 = [email protected] 
val b = new Point(3,4)    //> b : week1.OU2.Point = [email protected] 
val c = a+b       //> c : week1.OU2.Point = [email protected] 
c.x         //> res0: Int = 4 
c.y         //> res1: Int = 6 
+3

'a'는 어디에서'+'메소드를 얻을 수 있습니까? 그것이 아는 것은'Point' 타입입니다. 그것은 실제로 'PointInt' _라는 것을 알지 못합니다. 즉,'Point '의 리턴 타입이 의미하는 것입니다! 'Point'에'+'메소드를 추가한다는 의미였습니까? –

+1

Rex의 설명 외에도'PointInt'를'PointDouble'에 넘기고 싶다면'+'메소드는'Point'의 서브 클래스가 아니라'Point'를 취해야합니다. –

+0

Rex, 적용 메소드가 PointInt 객체를 주어야하지 않습니까? – Kevinw1983

답변

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를 사용하여 공용 인터페이스를 선언합니다.