快学Scala 第二十二课 (apply和unapply)

Posted AK47Sonic

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快学Scala 第二十二课 (apply和unapply)相关的知识,希望对你有一定的参考价值。

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, last@IsCompound()) => 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)的主要内容,如果未能解决你的问题,请参考以下文章

重学java基础第二十二课:IDEA安装

快学Scala 第二十一课 (初始化trait的抽象字段)

第二十二课 Shell的基础知识

第二十二课 单链表的具体实现

第二册二十二课

Golang✔️走进 Go 语言✔️ 第二十二课 json & 文件读写