Scala`类`的模式匹配

时间:2014-11-24 03:39:06

标签: scala pattern-matching

我尝试为该课程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

1 个答案:

答案 0 :(得分:4)

unapply的参数应该是您要匹配的类型的实例:

class Foo(val x: Int)

object {
    def unapply(f: Foo): Option[Int] = Some(f.x)
}