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