當(dāng)object部定義了unapply方法時(shí),該object稱(chēng)為extractor object态罪。
apply通常扮演構(gòu)造函數(shù)的角色:給定參數(shù)創(chuàng)建對(duì)象噩茄,而unapply則相反:根據(jù)對(duì)象解析出構(gòu)造對(duì)象的參數(shù)
extractor常用在模式匹配和偏函數(shù), case class默認(rèn)實(shí)現(xiàn)了unapply方法,因此它也是一個(gè)extractor
import scala.util.Random
object CustomerID {
def apply(name: String) = s"$name--${Random.nextLong}"
def unapply(customerID: String): Option[String] = {
val stringArray: Array[String] = customerID.split("--")
if (stringArray.tail.nonEmpty) Some(stringArray.head) else None
}
}
val customer1ID = CustomerID("Sukyoung") // Sukyoung--23098234908
customer1ID match {
case CustomerID(name) => println(name) // prints Sukyoung
case _ => println("Could not extract a CustomerID")
}
當(dāng)我們調(diào)用 case CustomerID(name) => println(name) 時(shí)向臀,就是調(diào)用了unapply方法巢墅,在IDEA中用快捷鍵找到方法定義時(shí),即達(dá)到unapply方法而不是構(gòu)造方法。
有時(shí)候extractor返回的參數(shù)并不是固定的君纫,可能是一個(gè)序列驯遇,這時(shí)候就可以定義unapplySeq方法,返回 Option[Seq[T]]蓄髓,如Regex
case r(name, remainingFields @ _*) =>.