Case Classes in Scala
November 26, 2019 Leave a comment
Case Classes (CCs) are very handy and powerful in scala. These are loaded with lot of important features than normal classes that we may need majority of the times. Some of the features are
1. class parameters are promoted to class fields (no need of explicit val declaration)
val p1 = new Person("ntalla", 26) println(p1.name)
2. Sensible toString is implemented
println(p1) // gives readable object notation instead of some default hash address
3. equals and hashCode implementations: This reason makes case classes particularly important in collections
val p2 = new Person("ntalla", 26) println(p1 == p2) // this will return true
4. Handy copy methods
val p2Copy = p2.copy(name = "ntallapa") println(p2Copy)
5. CCs have companion objects
val thePerson = Person // this is the companion object that is created by case class // this system created companion object will also have some handy factory methods val ntalla = Person("ntalla1", 26) // this is apply method on companion object // companion apply method does the same thing as that of the class constructor
6. CCs are serializable
// this feature makes CCs very useful in distributed systems where objects are sent over the network across JVMs
7. CCs have extractor patterns = CCs can be used in PATTERN MATCHING (another very very powerful feature)
Anonymous Classes
Giving implementation without a name. Anonymous implementation can be done for Normal Classes, Abstract Classes and also Traits
abstract class Animal { def eat: Unit } // giving implementation to abstract class without naming it - Anonymous val funnyAnimal: Animal = new Animal { override def eat: Unit = println("akdhasks") } // proof of instance on abstract class println(funnyAnimal.getClass) // We can also create anonymous class for normal classes // as well along with traits and abstract classes class Person(name: String) { def sayHi: String = s"$name said hello" } val p1 = new Person("ntalla") { override def sayHi: String = s"${super.sayHi} and welcome" }
Recent Comments