我尝试为该课程unapply
实施Foo
:
object Foo {
def unapply(x: Int): Option[Int] = Some(x)
}
class Foo(x: Int)
然而,当我尝试使用它时它在REPL中失败:
scala> val f = new Foo(100)
scala> f match { case Foo(x) => x }
<console>:13: error: pattern type is incompatible with expected type;
found : Int
required: Foo
f match { case Foo(x) => x }
为什么我不能使用我为此示例创建的unapply
?
答案 0 :(得分:4)
unapply
的参数应该是您要匹配的类型的实例:
class Foo(val x: Int)
object {
def unapply(f: Foo): Option[Int] = Some(f.x)
}