2013-03-29 11 views
2

我在使用f-bound類型參數時出現自定義提取器時出現問題。以下作品:模式匹配/提取器失敗(由於選項是協變的)

trait Bar 

object Model { 
    object Foo { 
    def unapply[A <: Bar](foo: Foo[A]): Option[Foo[A]] = Some(foo) 
    } 
    trait Foo[A <: Bar] extends Model[A] 
} 
trait Model[A <: Bar] 

object View { 
    def apply[A <: Bar](model: Model[A]): View[A] = model match { 
    case Model.Foo(peer) => new Foo(peer) 
    } 
    class Foo[A <: Bar](val peer: Model.Foo[A]) extends View[A] 
} 
trait View[A <: Bar] 

但它發生故障時Bar是F-界:

trait Bar[B <: Bar[B]] 

object Model { 
    object Foo { 
    def unapply[A <: Bar[A]](foo: Foo[A]): Option[Foo[A]] = Some(foo) 
    } 
    trait Foo[A <: Bar[A]] extends Model[A] 
} 
trait Model[A <: Bar[A]] 

object View { 
    def apply[A <: Bar[A]](model: Model[A]): View[A] = model match { 
    case Model.Foo(peer) => new Foo(peer) 
    } 
    class Foo[A <: Bar[A]](val peer: Model.Foo[A]) extends View[A] 
} 
trait View[A <: Bar[A]] 

造成這種錯誤:

<console>:12: error: inferred type arguments [A] do not conform to method unapply's 
    type parameter bounds [A <: Bar[A]] 
      case Model.Foo(peer) => new Foo(peer) 
        ^
<console>:12: error: type mismatch; 
found : Model.Foo[A(in method unapply)] 
required: Model.Foo[A(in method apply)] 
      case Model.Foo(peer) => new Foo(peer) 
             ^

我懷疑的問題是,unapply的返回類型是Option[+A]並且A不是不變的。這是這個問題的起源嗎?我怎麼能解決這個問題?

回答

0

雖然沒有回答一個是否可以創建一個工作unapply方法,斯卡拉2.10的模式匹配至少不抱怨基於鑄模式匹配與不變的類型參數的任何更多:

object View { 
    def apply[A <: Bar[A]](model: Model[A]): View[A] = model match { 
    case peer: Model.Foo[A] => new Foo(peer) // yippie, no problem having `[A]` here 
    } 
    class Foo[A <: Bar[A]](val peer: Model.Foo[A]) extends View[A] 
} 
trait View[A <: Bar[A]]