Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between case class and case object?

Tags:

scala

akka

I am learning Scala and Akka and in my recent lookup for a solution, I found something like

 case class TotalTaxResult(taxAmount:Double)  case object TaxCalculationTimeout 

What is the difference between the two?

When should I use one over the other?

like image 239
daydreamer Avatar asked Aug 18 '15 17:08

daydreamer


People also ask

What is difference between Case class and case object in Scala?

A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).

What is difference between class and case class?

A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).

What is a case object?

A case object is like an object , but just like a case class has more features than a regular class, a case object has more features than a regular object. Its features include: It's serializable. It has a default hashCode implementation. It has an improved toString implementation.

What is a case class?

A case class has all of the functionality of a regular class, and more. When the compiler sees the case keyword in front of a class , it generates code for you, with the following benefits: Case class constructor parameters are public val fields by default, so accessor methods are generated for each parameter.


1 Answers

A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).

If your message to your actor does not need any value differentiation, use a case object. For instance, if you had an actor that did some work, and you, from the outside, wanted to tell it to do work, then maybe you'd do something like this:

case object DoWork  ...  def receive = {   case DoWork =>       //do some work here } 

But if you wanted some variation in how the work is done, you might need to redefine your message like so:

case class DoWorkAfter(waitTime:Long)  ...  def receive = {   case class DoWorkAfter(time) =>     context.system.scheduler.scheduleOnce(time.milliseconds, self, DoWork)    case DoWork =>       //do some work here } 
like image 115
cmbaxter Avatar answered Sep 22 '22 09:09

cmbaxter