A custom extraction can be written by implementing the unapply
method and returning a value of type Option
:
class Foo(val x: String)
object Foo {
def unapply(foo: Foo): Option[String] = Some(foo.x)
}
new Foo("42") match {
case Foo(x) => x
}
// "42"
The return type of unapply
may be something other than Option
, provided the type returned provides get
and isEmpty
methods. In this example, Bar
is defined with those methods, and unapply
returns an instance of Bar
:
class Bar(val x: String) {
def get = x
def isEmpty = false
}
object Bar {
def unapply(bar: Bar): Bar = bar
}
new Bar("1337") match {
case Bar(x) => x
}
// "1337"
The return type of unapply
can also be a Boolean
, which is a special case that does not carry the get
and isEmpty
requirements above. However, note in this example that DivisibleByTwo
is an object, not a class, and does not take a parameter (and therefore that parameter cannot be bound):
object DivisibleByTwo {
def unapply(num: Int): Boolean = num % 2 == 0
}
4 match {
case DivisibleByTwo() => "yes"
case _ => "no"
}
// yes
3 match {
case DivisibleByTwo() => "yes"
case _ => "no"
}
// no
Remember that unapply
goes in the companion object of a class, not in the class. The example above will be clear if you understand this distinction.