2

我对使用 f 有界类型参数时出现的自定义提取器有疑问。以下作品:

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

4

1 回答 1

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]]
于 2013-03-29T16:08:14.123 回答