Pattern matching is a powerful "protocol" for extracting data inside data structures in a controlled way.
Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.
This functional concept allows us to
If an object performs stateful computations on the inside or exhibits other kinds of complex behavior, it should be an ordinary class.
Matching on Variable Argument Lists
case class WhereIn[T](column:String, val1:T, vals:T*)
where match {
case w @ WhereIn(col, val1, vals @_*)=>
val valStr = (w.val1 +: w.vals).mkString(",")
}
Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.
This functional concept allows us to
- use a compact initialization syntax (
Node(1, Leaf(2), None))
) - decompose them using pattern matching
- have equality comparisons implicitly defined
If an object performs stateful computations on the inside or exhibits other kinds of complex behavior, it should be an ordinary class.
Case classes differ from regular classes in that they get:
- pattern matching support
- default implementations of
equals
andhashCode
- default implementations of serialization
- a prettier default implementation of
toString
A case class gets a companion object that has a factory method named apply, which is used for construction. And another method called unapply, which is used for extraction or "deconstruction". It is invoked when a pattern-math expression is encountered.
person match {
case Person("Alice", 25, Address(_,"Chicago", _)) => ...
}
Scala looks for Person.unapply() and Address.unapply() and calls them.
All unapply methods return an Option(TupleN), where N is the number of values that can be extracted from the object.
object Person{
def apply(name:String, age:Int, address:Address) =
new Person(name, age, address)
def unapply(p:Person):Option[Tuple3[String, Int, Address]]=
Some((p.name, p.age, p.address))
}
The unapply methods are invoked recursively, if necessary.
To return a sequence of extracted items, rather than a fixed number of them, we use unapplySeq method. A Seq companion object implements apply and unapplySeq, but not unapply.
Matching on Variable Argument Lists
case class WhereIn[T](column:String, val1:T, vals:T*)
where match {
case w @ WhereIn(col, val1, vals @_*)=>
val valStr = (w.val1 +: w.vals).mkString(",")
}
No comments:
Post a Comment