2013-09-30 7 views
0

일부 요소의 인스턴스 (내부 형식)를 만드는 팩토리 개체가 있습니다. 또한 공장에서 만든 요소에서 작동하는 작업이 있습니다.추상 클래스를 사용하지 않고 형식 유추를 수행하는 방법

class Factory { 
    class Element private [Factory] (val int:Int) 
    def create(from:Int) = new Element(from) 
} 

class OperationOnFactoryElement(val factory:Factory) { 
    def apply(element:factory.Element) = factory.create(element.int + 1) 
} 

val factory = new Factory 

val op = new OperationOnFactoryElement(factory) 

val someElement = factory.create(1) 

op(someElement) // this causes an error!! 

//<console>:13: error: type mismatch; 
// found : factory.Element 
// required: op.factory.Element 
//    op(someElement) 
//    ^

컴파일러가 작업을 허용하도록 OperationOnFactoryElement에 포함 된 공장을 사용하는 날을 기대하고 분명하다 : 여기에 코드입니다. 그러나 그 요소에 대해 더 많은 연산을 정의해야한다면, 예를 들어 두 연산을 결합 할 수 없기 때문에 문제가됩니다. 이 솔루션을 생각해 냈습니다 :

class Factory { 
    class Element private [Factory] (val int:Int) 
    def create(from:Int) = new Element(from) 
} 

abstract class OperationOnFactoryElement { 
    val factory:Factory 
    def apply(element:factory.Element) = factory.create(element.int + 1) 
} 

val myfactory = new Factory 

val op = new OperationOnFactoryElement { 
val factory:myfactory.type = myfactory 
} 
val someElement = myfactory.create(1) 

op(someElement) // this works 

그러나 저는 작업을 추상 클래스로 변경해야합니다. 내 질문 :

클래스를 만들지 않고 같은 결과를 얻을 수있는 방법이 있나요 OperationOnFactoryElement 추상?

답변

2

당신은 Element이 변경으로 Factory

class OperationOnFactoryElement(val factory:Factory) { 
    def apply(element:Factory#Element) = factory.create(element.int + 1) 
} 

내에서 정의 된 기대 apply에게 Factory#Element를 사용할 수있는 코드의 첫 번째 예는 다음과 같이 작동합니다.

scala> class Factory { 
    | class Element private [Factory] (val int:Int) 
    | def create(from:Int) = new Element(from) 
    | } 
defined class Factory 

scala> class OperationOnFactoryElement(val factory:Factory) { 
    | def apply(element:Factory#Element) = factory.create(element.int + 1) 
    | } 
defined class OperationOnFactoryElement 

scala> val factory = new Factory 
factory: Factory = [email protected] 

scala> val op = new OperationOnFactoryElement(factory) 
op: OperationOnFactoryElement = [email protected] 

scala> val someElement = factory.create(1) 
someElement: factory.Element = [email protected] 

scala> op(someElement) 
res0: op.factory.Element = [email protected] 

scala> someElement.int 
res1: Int = 1 

scala> res0.int 
res2: Int = 2 
관련 문제