1

I attempted to implement unapply for the class, Foo:

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

class Foo(x: Int) 

However, it fails in the REPL when I attempt to use it:

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 }

Why can't I use the unapply that I created for this example?

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

4

The argument of unapply should be an instance of the type you want to match:

class Foo(val x: Int)

object {
    def unapply(f: Foo): Option[Int] = Some(f.x)
}
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138