Case class-an Ultra POJO class in Scala

POJO stands for Plain-Old Java Object, a class that will have set of fields and their getters and setters. Pojo class is primarily used as a data structure or data carrier across the layers in the J2EE applications. It is understood as more of a best practice than a language standard to define one using any special keyword like pojo. 

Is there any equivalent of such class in Scala? yes there is. But not just for a data structure but with valiant features to cater in various usage. 

Case comes with handy 

Case class in Scala is used for the purpose of defining an object with immutable data. On the otherhand, when a class is defined as a Case class, a lot of boilerplate code is generated by the Scala compiler. The methods like apply, unapply, tupled, copy, set of accessors and mutators, and objects default methods like toString, hashCode, and equals are part of the generated boilerplate code.

A question might pop-up in our mind, Isn’t a case class similar to java POJO(Plain-Old Java Object) class? The answer is yes only on the getters and setters dimension, apart from that case class has lot more features to be different from the POJO class.

The following code snapshot depicts the declaration of case class and its instantiation in a driver class. 



Immutable record

Case class constructor parameters are immutable by default, they are declared with val. However, the parameters can be declared as var explicitly.

// declaring edition argument as mutable
case class Book(name: String, author: String, pages: Int, var edition: String)
var b = Book(“Angular 4”, “Tom Lee”, 430, “1st”)
b.edition = “2nd 2017”



Comments

Popular posts from this blog

Trait, an interface in Scala

Singleton class made easy in Scala

Quickstart with Angular 2/4