- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
How does a case class differ from a normal class?
Created by admin on 2008-07-28.
Updated: 2008-07-28, 16:34
- You can do pattern matching on it,
- You can construct instances of these classes without using the
new
keyword, - All constructor arguments are accessible from outside using automatically generated accessor functions,
- The
toString
method is automatically redefined to print the name of the case class and all its arguments, - The
equals
method is automatically redefined to compare two instances of the same case class structurally rather than by identity. - The
hashCode
method is automatically redefined to use thehashCode
s of constructor arguments.
Most of the time you declare a class as a case class because of point 1, i.e. to be able to do pattern matching on its instances. But of course you can also do it because of one of the other points. The code example below makes use of two of the characteristics of case classes:
- Instances are created without resorting to the
new
keyword (point 2), for example inList(MyInt(1), MyInt(2), MyInt(3))
- Constructor arguments are accessed from "outside" using the automatically generated accessor functions (point 3), in
else m.asInstanceOf[MyInt].x == x;