Sunday, 4 January 2015

Case Class in Scala


Case classes are primarily intended to create “immutable records” that you can easily use in pattern-matching expressions. Perhaps as a result of this, case class constructor parameters are val by default.

Defining a class as a case class results in a lot of boilerplate code being generated, with the following benefits:

  • An apply method is generated, so you don’t need to use the new keyword to create a new instance of the class.
     scala> case class Person(name: String, reltion: String)
     scala> val emily = Person("Emily", "niece")
  • Accessor methods are generated for the constructor parameters because case class constructor parameters are val by default. Mutator methods are also generated for parameters declared as var.
  • A good, default toString method is generated.
  • An unapply method is generated, making it easy to use case classes in match expressions.
      scala> emily match {case Person(n, r) => println(n, r)}
  • equals and hashCode methods are generated.
  • A copy method is generated.

No comments:

Post a Comment