-2

I understand that using something like

case class private A()

new A()#This will be a invalid call as A is private

But what I do not understand that as from an implementation perspective, what advantage does this provide while coding? Because calling A() twice will give 2 instances of the class anyways. If this syntax is not used to prevent instantiation like Java, then why would I want to not let someone instantiate my class using new?

Todd
  • 30,472
  • 11
  • 81
  • 89
Viraj Rai
  • 75
  • 2

1 Answers1

0

Marking a case class constructor private is useless. As you've notices, case classes get a synthetic companion object with an apply method whose implementation is simply a call to the actual constructor.

Scala case classes have been designed to just "classes + the case modifier", meaning that everything that works on classes also works on case classes, which also include the (pointless) ability to specify access modifiers on the constructor.

OlivierBlanvillain
  • 7,701
  • 4
  • 32
  • 51
  • Agree that it's not very useful. Scala case classes do give you a few more things than the apply method in the companion object. (e.g. `unapply`). If there is a useful scenario, it might be one where you'd want to prevent direct instantiation but still want pattern matching. I'm a little reluctant to say that this would never be needed, but I certainly can't think of an example. – sfosdal Jun 07 '17 at 23:25