快学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(" ")
  }
}

运行结果:

 

转载于:https://www.cnblogs.com/AK47Sonic/p/7787085.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值