unapply again

scala

boolean test / unapply in class

  1. unapply should return boolean or Option to be used in pattern match.
  2. unapply returns boolean is used to do some test of the subject, e.g
class Person(val name: String, val age: Int)
object Person {
	def unapply(person: Person): Boolean = (person.age == 10)
	def main(args: Array[String]): Unit = {
		val p = new Person("leecy", 10)
		p match {
			case Person() => println("10 years old")
			case _ => println("not 10")
		}
	}
}

  1. unapply defined in class can also be used in pattern match, the class instance now works as the extractor object. For example,
class Person(val name: String, val age: Int) {
	// both are ok but should be used with the instance
	def unapply(person: Person): Boolean = (person.age == 10)
	// def unapply(person: Person): Option[(String, Int)] = Some(person.name->person.age)
}
object Person {
	
	def main(args: Array[String]): Unit = {
		val p = new Person("leecy", 10)
		p match {
			case p() => println("10 years old") // use the instance p 
			case _ => println("not 10")
		}
	}
}