快學Scala 第二十二課 (apply和unapply)

來源:互聯網
上載者:User

標籤:def   private   mat   inpu   ons   try   case   ast   sky   

apply和unapply:

 

apply方法經常用在伴生對象中,用來構造對象而不用顯式地使用new。

unapply是當做是伴生對象的apply方法的反向操作。apply方法接受構造參數,然後將他們變成對象。而unapply方法接受一個對象,然後從中提取值。unapply方法返回的是一個Option.

object ScalaRunner {  def main(args: Array[String]): Unit = {    testApply2()    testApplyUnApply()    testCaseClass()    testNumber()    testUnapplyCheck()  }  private def testUnapplyCheck(): Unit = {    "Hello World fdf" match {      case Name(first, [email protected]()) => println(s"first: ${first}, last: ${last}")    }  }  private def testNumber() = {    val Number(n) = "12345"    println(s"n: ${n}")  }  private def testCaseClass(): Unit = {    val p: Person = Person("Sky", 20)    p match {      case Person(name, 20) => println(s"name: ${name}")    }  }  private def testApplyUnApply() {    val nameObj = Name("hello", "world")    println(s"a: ${nameObj.a}, b: ${nameObj.b}")    val Name(arg11, arg12) = "Hello World"    println(s"arg11: ${arg11}, arg12: ${arg12}")    val Name(arg21, arg22) = Name("hello", "world").toString    println(s"arg21: ${arg21}, arg22: ${arg22}")  }  private def testApply(): Unit = {    Name()    (new Name) ()    (new Name()) ()    Name()()  }  private def testApply2(): Unit = {    Name(1)    (new Name()) (1)    (new Name) (1)    Name(1)(1)  }}case class Person(val name: String, val age: Int)object Number {  def unapply(input: String): Option[Int] = {    try{      Some(Integer.parseInt(input.trim))    } catch {      case ex: NumberFormatException => None    }  }}class Name {  var a = ""  var b = ""  def this(a: String, b: String){    this    println("Call class construct.")    this.a = a    this.b = b  }  def apply() = {    println("Call class apply.")  }  def apply(i: Int) = {    println(s"Call class apply ${i}.")  }  override def toString: String = {    a + " " + b  }}object Name {  def apply(): Name = {    println("Call object apply.")    new Name()  }  def apply(i: Int): Name = {    println(s"Call object apply ${i}.")    new Name()  }  def apply(a: String, b: String): Name = {    println(s"Call object apply.")    new Name(a, b)  }  def unapply(input: String): Option[(String, String)] = {    println(s"Call object unapply.")    val pos = input.indexOf(" ")    if(pos == -1) None    else Some((input.substring(0, pos), input.substring(pos + 1)))  }}object IsCompound {  def unapply(input: String) = {    println(s"Call IsCompound unapply ${input}.")    input.contains(" ")  }}

運行結果:

 

快學Scala 第二十二課 (apply和unapply)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.