top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is case class? What is case object? What are the Advantages of case class?

+1 vote
431 views
What is case class? What is case object? What are the Advantages of case class?
posted Sep 28, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The main advantage or aim of Case Class concept is that to ease the development by avoiding lot of boilerplate code. We can use Case Classes in Pattern Matching very easily.

What is Case Class?

Case class is also a class, which is defined with “case” modifier. Because of this “case” keyword, we will get some benefits to avoid boilerplate code.

Example:-

scala> case class Employee(name:String)
defined class Employee
Here we have defined a case class with name “Employee” and with one parameter “name”.

What is Case Object?

Case object is also an object which is defined with “case” modifier. Because of this “case” keyword, we will get some benefits to avoid boilerplate code.

Example:

scala> case object Employee
defined object Employee

Here we have defined a case object with name “Employee”.

Scala’s Case Class Benefits In Brief

Case class is also a class, however when we compare it with normal class, it gives us some extra features or benefits.

The following are the complete list of Advantages/Benefits of Scala’s Case class:

By default, Scala Compiler adds toString, hashCode and equals methods. We can avoid writing this boilerplate code.

By default, Scala Compiler adds companion object with apply and unapply methods that’s why we don’t need new keyword to create instances of a case class.

By default, Scala Compiler adds copy method too.

We can use case classes in Pattern Matching.

By default, Case class and Case Objects are Serializable.

By using Case Classes, we can define Algebraic data types (ADT).

They improve productivity that means it avoids writing lot of boilerplate code so that Developers can deliver a functionality with less effort.

answer Oct 3, 2016 by Shyam
...