# apply() 與 unapply() 方法

``case class Apple(price: Int, weight: Int)val apple = Apple(10, 20)val Apple(p, w) = appleprintln(p)    // 10println(w)    // 20``

``def separate(s: String) = {    val parts = s.split(",")    if(parts.length == 3) (parts(0), parts(1), parts(2)) else None}val (number, name, addr) = separate("B123456,Justin,Kaohsiung")println(number)   // B123456println(name)     // Justinprintln(addr)     // Kaohsiung``

separate()函式傳回三個元素的Tuple，你運用了Tuple模式比對的特性傳回分割後的個別字串。然而，如果你可以這麼作的話，程式看起來會更清楚：
``// 這有可能嗎？val Student(number, name, addr) = "B123456,Justin,Kaohsiung"``

``object Student {    def unapply(str: String): Option[(String, String, String)] = {        val parts = str.split(",")        if (parts.length == 3) Some(parts(0), parts(1), parts(2)) else None    }}val Student(number, name, addr) = "B123456,Justin,Kaohsiung"println(number)   // B123456println(name)     // Justinprintln(addr)     // Kaohsiung``

unapply()方法可以接受你所提供的物件（在這邊是以字串為例，事實上可以是任何類型），經用你所定義的unapply()方法內容處理後傳回Option物件，事實上，在上例的例子中，編譯器會作如下的處理：
``val Some((number, name, addr)) = Student.unapply("B123456,Justin,Kaohsiung")``

unapply()方法稱之為提取方法（Extraction method），而像Student這樣只具備提取方法的物件稱之為提取器（Extractor），提取器讓你對非案例類別的實例，也可以進行模式比對，例如搭配match運算式的一個例子如下：
``val students = List(                   "B123456,Justin,Kaohsiung",                   "B98765,Monica,Kaohsiung",                   "B246819,Bush,Taipei"               )students.foreach(_ match {    case Student(nb, name, addr) => println(nb + ", " + name + ", " + addr)})``

``val students = List(                   "B123456,Justin,Kaohsiung",                   "B98765,Monica,Kaohsiung",                   "B246819,Bush,Taipei"               )               students.foreach(_ match {    case Student(_, name, addr) if addr == "Kaohsiung" => println(name)    case _ =>})``

``object Student {    def apply(number: String, name: String, addr: String) = {        number + "," + name + "," + addr    }        def unapply(str: String) = {        val parts = str.split(",")        if (parts.length == 3) Some(parts(0), parts(1), parts(2)) else None    }}``

``val number = readLineval name = readLineval addr = readLineval data = Student(number, name, addr)println(data)   // 實際也許是寫入文字檔案``