scala extractor object

scala

unapply

Object which defines an unapply method that returns an Option is an extractor. If there are multiple fields can be extracted, return an Option of Tuple. See below:

// not a case class
class Person(val name: String, val age: Int)

object Person {

	// define an extractor
  def unapply(s: Person): Option[(String, Int)] = Some(s.name -> s.age)

  def main(args: Array[String]): Unit = {
    val s = new Person("lcy", 31)
    s match {
			// it's like Person.unapply(s)
      case Person(n, a) => println(n, a)
      case _ => println("")
    }
  }

}

Next is a real example from spark code. NotFatal object defines an unapply method to check whether a Throwable is fatal.

e3ec488d-9a7e-4da9-8a9c-c96f6671b4c7