This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I am learning Scala. I am kind of stuck with the concept of Case Classes. Could somebody please explain me this in simple terms?
Do we have something similar in Java? I ask because I am a Java programmer and it would be easier to understand this if we have something similar in Java.
There is no real Java analog to case classes. Case classes in Scala are regular classes with some sytactic sugar added. Specifically, the compiler a toString method, and it generates a companion object with 'special' apply and unapply methods. The key thing to remember with case classes is that you don't have to use the keyword 'new' to create an instance (because of the compiler generated apply method), and they can be used out of the box in pattern matches (because of the compiler generated unapply method).
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Joined: May 01, 2008
Thanks Garret. I got your point.
Joined: May 01, 2008
Is Case Class very commonly used?
Where can I study scala pattern matching in detail? I am going through the details of scala-lang.org site and the pdf files (Scala tutorial) from the site. Is there any simpler and elaborative explanation available? I am kind of weak in pattern matching.
Joined: Jan 17, 2006
Case classes are quite common in Scala, as is pattern matching. The most common cases are pattern matching on Options or Lists. Using a case class for pattern matching in your own class heirarchy is realtively straightforward.
I wouldn't recommend overusing case classes. Scala Tips mentioned inheritance ambiguities with case classes.
In my little experience case classes help in small matters, in such points, where no extensions are planned (for example, in domain model parts, to avoid equals/hashCode boilderplates). They greatly increase readability in such cases. On the other hand, using them just to save three characters from unnecessary "new" keyword may introduce other concerns. Use them wisely.