Case Classes Are Cool - Code Commit
Of all of Scala's many features, this one has probably taken the most flack over the past year or so. Not immutable data structures or even structural types, but rather a minor variation on a standard object-oriented construct. This is more than a little surprising, especially considering how much work they can save when properly employed. Quick Primer Before we get into why they're so nice, we should probably look at what they are and how to use them.
What these developers fail to realize is that case classes are really much more than that, freeing us from the boiler-plate tyranny of endless getter/setter declarations and the manual labor of proper
Read full article from Case Classes Are Cool - Code Commit
Of all of Scala's many features, this one has probably taken the most flack over the past year or so. Not immutable data structures or even structural types, but rather a minor variation on a standard object-oriented construct. This is more than a little surprising, especially considering how much work they can save when properly employed. Quick Primer Before we get into why they're so nice, we should probably look at what they are and how to use them.
Syntactically, case classes are standard classes with a special modifier:
case
. This modifier signals the compiler to assume certain things about the class and to define certain boiler-plate based on those assumptions. Specifically:- Constructor parameters become public “fields” (Scala-style, which means that they really just have an associated accessor/mutator method pair)
- Methods
toString()
,equals()
andhashCode()
are defined based on the constructor fields - A companion object containing:
- An
apply()
constructor based on the class constructor - An extractor based on constructor fields
- An
equals()
method and the automatic conversion of the constructor parameters into fields. Considering how many times I have built “Java Bean” classes solely for the purpose of wrapping data up in a nice neat package, it is easy to see where this sort of syntax sugar could be useful.case class Person(var firstName: String, var lastName: String) val me = Person("Daniel", "Spiewak") me.firstName = "Christopher" // call to a mutator |
What these developers fail to realize is that case classes are really much more than that, freeing us from the boiler-plate tyranny of endless getter/setter declarations and the manual labor of proper
equals()
and toString()
methods. Case classes are the object-oriented developer’s best friend, just no one seems to realize it yet.Read full article from Case Classes Are Cool - Code Commit
No comments:
Post a Comment