【发布时间】: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