2012-11-06 49 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

相關問題