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

    运行结果:

  • 相关阅读:
    SQL SERVER将远程服务器的数据库备份到本地文件夹
    c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)
    CentOS 7 服务器配置安装CentOS 7
    String,StringBuffer与StringBuilder
    springmvc常用注解标签详解【转】
    第一个SpringMVC实例和解析(HelloSpringMVC)
    排序算法总结及Java实现
    MySQL实例
    Java集合框架梳理(含经典面试题)
    面试妆容
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7787085.html
Copyright © 2020-2023  润新知