Wednesday, October 23, 2013

Case Class


Many of us use Case Class very often in Scala Programming. Let's see how it works,

case class Student(name: String, address: String) {
}

val s = Student("Suresh", "Fremont")

The above statement shows you don't need "new" keyword to create an instance of case class? 

Scala creates a method "apply" internally for each case class. The above statement calls apply (...) of Student to create instances. Inside the apply()...new operator is used to create the class instance.

As per official Scala website, they claim case classes are regular classes. But I'm not fully convinced with it because,

i. case class should always have constructor parameters.
ii. polymorphism is not possible with case class i.e., overloaded constructors..
iii. the constructor parameters are public by default
etc.,

The operations you can do with case class, 

==, != --> equality check
case/pattern matching 





No comments:

Post a Comment