- 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
newkeyword, - All constructor arguments are accessible from outside using automatically generated accessor functions,
- The
toStringmethod is automatically redefined to print the name of the case class and all its arguments, - The
equalsmethod is automatically redefined to compare two instances of the same case class structurally rather than by identity. - The
hashCodemethod is automatically redefined to use thehashCodes 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
newkeyword (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;









