【问题标题】:Pattern matching / extractor fails (due to Option being covariant)模式匹配/提取器失败(由于 Option 是协变的)
【发布时间】:2013-03-20 08:22:57
【问题描述】:

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

【问题讨论】:

    标签: scala pattern-matching covariance


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多