标签: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, 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(" ") } }
运行结果:
标签:def private mat inpu ons try case ast sky
原文地址:http://www.cnblogs.com/AK47Sonic/p/7787085.html