模式匹配/提取器失败(由于Option是协变的)

时间:2013-03-29 15:44:55

标签: scala pattern-matching covariance

我在使用f-bounded类型参数时出现自定义提取器问题。以下作品:

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受到限制时它会崩溃:

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不是不变的。这是这个问题的根源吗?我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:0)

虽然没有回答是否可以创建一个有效的unapply方法,但Scala 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]]