2

I read and understand, case class is to send arguments and create multiple object and case object don't send any arguments and having single object. So that will achieve by object also why case object.

Why is case object important and when? I already gone through this post, but I did not get why case object.

Difference between case class and case object?

halfer
  • 19,824
  • 17
  • 99
  • 186
Sun
  • 3,444
  • 7
  • 53
  • 83

1 Answers1

0

Well... an object in Scala can be "roughly" explained as an instance of an anonymous class. Now the difference in a case object and object lies in the difference of that anonymous class being a case class or just a class

To put it more clearly,

object A

// is roughly equivalent to something like

class AnonymousClass12345
val A = new AnonymousClass12345()

Where as for case object,

case object A

// is roughly equivalent to something like,

case class AnonymousClass12345
val A = new AnonymousClass12345()

And now it should be very easy to relate to case class vs class. And as an instance of an anonymous case class, case object gets all the goodies that any instance of any other case class does.

Note :: This answer is meant to provide an inaccurate but easy to understand explanation. A more accurate answer of this question will require not only an understanding of the difference class vs type which is nicely (but not very accurately) discussed in this - answer but also of Scala reflection.

Community
  • 1
  • 1
sarveshseri
  • 13,738
  • 28
  • 47
  • `object A` is an instance of `A.type`, not an "anonymous class". – mikołak Oct 18 '16 at 10:27
  • In simple words, **case** mean immutable, am I right? – Sun Oct 18 '16 at 10:31
  • NO... as big NO. `case class` or `case object` have nothing to do with `immutability` – sarveshseri Oct 18 '16 at 10:54
  • @mikołak Well... I suppose you did not noticed `roughly` in `is roughly equivalent to something like`. Or are you ready to explain `what A.type is ?` to a Scala beginner like OP ? Edited the answer to emphasise more on `roughly`. – sarveshseri Oct 18 '16 at 11:01
  • @SarveshKumarSingh: 1. Moslty I noticed "is nothing but" at the very start of the original revision (now edited, thank you). 2. Yeah, sure, how does e.g. _`A` is an instance of an automatically generated "class" `A.type`_ sound? – mikołak Oct 18 '16 at 11:53
  • that `"class"`... :P – sarveshseri Oct 18 '16 at 12:12