Is apply and unapply a constructor in scala -
in java can make constructor using class name. in scala have seen different use of apply , unapply, same constructor in java, in can use apply , unapply constructor
apply()
can used factory method (not constructor), , is, not restricted or required so. makes apply()
special can "silently" invoked.
class myclass(arg: string) { def apply(n: int):string = arg*n } val mc = new myclass("blah") mc.apply(2) // res0: string = blahblah mc(3) // res1: string = blahblahblah
you'll see apply()
used factory method in companion object.
object myclass { def apply(s: string): myclass = new myclass(s) } val mc = myclass("bliss") // call object's apply() method
but, again, that's convenient convention, not requirement.
unapply()
(and unapplyseq()
) different in "silently" called whenever attempt pattern match on class instance.
class myclass(val arg: string) {} object myclass { def unapply(x: myclass): option[string] = some(x.arg) } val mc = new myclass("bland") mc match { case myclass(s) => println(s"got $s") // output: "got bland" case _ => println("not") }
Comments
Post a Comment