2012-11-06 3 views
5

다음 코드에 문제가 있습니다. 컴파일되지 않습니다. 누구나 asInstanceOf [SomeImpl] 또는 패턴 일치를 사용하지 않고 컴파일하는 방법을 알고 있습니까?하위 클래스의 특정 매개 변수 유형을 사용할 수 없습니다.

나는 상한 또는 하한을 사용하여 몇 가지 유형 매개 변수를 생각하고 있습니다.

object InherenceTryout extends App { 

    import someimpl._ 

    val list = List(SomeImpl("A"), SomeImpl("B")) 
    val result = new SomeHandler().handleBaseList(list) 

    println("%s->%s" format (list, result)) 

} 

package base { 

    // Defines that a 'Base' object can create a new 
    // 'Base' object where another 'Base' object is mixed in 
    // Does not define how the mixing will take place 
    trait Base { 
    def mix(other: Base): Base 
    } 

    // Defines how a default 'Base' object gets mixed into a list of 'Base' objects 
    trait BaseHandler { 
    def defaultBase: Base 
    def handleBaseList(list: List[Base]): List[Base] = list.map(b => b.mix(defaultBase)) 
    } 

} 

package someimpl { 

    import base._ 

    // Some implementation of 'Base' 
    // Defines how a new 'SomeImpl' object is created by mixing in another 
    // 'SomeImpl' object 

    // ERROR: 
    // class SomeImpl needs to be abstract, since method mix in trait Base of type (other: base.Base)base.Base is not defined 
    // (Note that base.Base does not match someimpl.SomeImpl: class SomeImpl in 
    // package someimpl is a subclass of trait Base in package base, but method parameter types must match exactly.) 
    case class SomeImpl(id: String) extends Base { 
     def mix(other: SomeImpl): SomeImpl = SomeImpl("[%s|%s]" format (id, other.id)) 
    } 

    // Defines the default 'SomeImpl' object 
    class SomeHandler extends BaseHandler { 
    def defaultBase = SomeImpl("D") 
    } 

} 

답변

4

사용 유형 매개 변수 :

package base { 

    trait Base[T <: Base[T]] { 
    def mix(other: T): T 
    } 

    trait BaseHandler[T <: Base[T]] { 
    def defaultBase: T 
    def handleBaseList(list: List[T]): List[T] = 
     list.map(b => b.mix(defaultBase)) 
    } 

} 

package someimpl { 

    import base._ 

    case class SomeImpl(id: String) extends Base[SomeImpl] { 
    def mix(other: SomeImpl): SomeImpl = SomeImpl("[%s|%s]" format (id, other.id)) 
    } 

    class SomeHandler extends BaseHandler[SomeImpl] { 
    def defaultBase = SomeImpl("D") 
    } 

} 
+0

이 대답은 매우 멋지지만 형식 매개 변수를 유추 할 수있는 또 다른 솔루션이있을 것입니다. 어쩌면 믹스 방법에 넣는 것일까 요? (실제로 나는 그것을 시도했지만 성공하지 못했습니다) – wwagner4

관련 문제