Apply and unapply:
The Apply method is often used in associated objects to construct an object without explicitly using new.
Unapply is the reverse operation of the Apply method as a companion object. The Apply method accepts the construction parameters and then turns them into objects. The Unapply method accepts an object and then extracts the value from it. The Unapply method returns an option.
Object Scalarunner {def main (args:array[string]): Unit = {testApply2 () testapplyunapply () Testcaseclass () Testnumber () Testunapplycheck ()} private Def testunapplycheck (): Unit = {' Hello world fdf ' match {case Nam E (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 "," p match {case person (name, p) = 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 Prin TLN (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 (INP Ut.trim)} catch {case ex:numberformatexception = none}}}class Name {var a = "" var b = "Def th Is (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 ("")}}
Operation Result:
Learn the Scala 22nd lesson (apply and unapply)