Sun
Sun

Reputation: 3564

Scala - what is case class private

I am analyzing my existing project, I found some this like this(conceptually):

case class AA private(id: String) {}

case class BB(id: String) {}

After I created those two classes to observe the difference. I analysed their java source by using java decompiler. I did not find any different.

What is the need of private there.

What is the importance of that.

Upvotes: 2

Views: 1583

Answers (2)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

You can understand this better using Scala REPL

scala> case class A private(a: String)
defined class A

scala> new A("")
<console>:14: error: constructor A in class A cannot be accessed in object $iw
       new A("")
       ^

scala> A("")
res3: A = A()

Notice that instantiation of the A cannot be done using new keyword. private helps restrict the instantiation of A using new(makes it private)

Upvotes: 3

A Spoty Spot
A Spoty Spot

Reputation: 746

A case class is a class which gets a Companion object automatically defined with a few helper functions. One of these is an apply method which essentially allows to skip out the 'new' keyword when defining a class. The private keyword in your example makes the constuction of a new AA using the 'new' keyword private. Eg:

case class A private(id: Int)
case class B(id: Int)
A(1) //Using public method
B(1) //Using public method
new A(1) // Using PRIVATE method
new B(1) // Using public method

Upvotes: 5

Related Questions