0

In the book, "Programming in Scala 5th Edition", it is mentioned in the fourth chapter that we can create class' objects using the following way if a class is a case class:

scala> case class Person(name: String, age: Int)
// defined case class Person

scala> val p = Person("Sally", 39)
val p: Person = Person(Sally,39)

I do not find it different from the following normal way:

scala> class Person(name: String, age: Int)
// defined class Person

scala> val p = Person("Aviral", 24)
val p: Person = Person@7f5fcfe9

I tried accessing the objects in both the cases and there was a difference. When I declare the same class as a case class, I can access its members: p.name, p.age whereas if I try to do the same with a normally declared class, I get the following error:

1 |p.name
  |^^^^^^
  |value name cannot be accessed as a member of (p : Person) from module class rs$line$3$.

How are the two cases different as far as constructing an object is considered?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Aviral Srivastava
  • 4,058
  • 8
  • 29
  • 81
  • 1
    Have you reviewed the answers found [here](https://stackoverflow.com/q/2312881/4993128)? – jwvh May 07 '21 at 21:00
  • 2
    @jwvh I was considering clicking on your link and closing this as duplicate. However, I found only a horrendously long wall of someone's vaguely related overly broad answers from 2010, 2013, 2017, and I don't know when else. I don't think that it's helpful to suggest to newcomers asking about Scala-3 to read everything that has been written since 2010. – Andrey Tyukin May 07 '21 at 21:47
  • 1
    This [here](https://stackoverflow.com/questions/61722892/are-case-class-constructor-parameters-public-val-fields-by-default) is also not a good duplicate, because it has a different focus. – Andrey Tyukin May 07 '21 at 21:52
  • 2
    @AndreyTyukin Maybe https://stackoverflow.com/questions/18194005/why-are-constructor-parameters-made-into-members-for-case-classes or https://stackoverflow.com/questions/24113964/whats-the-difference-between-class-and-case-class-in-stream-in-scala – Mario Galic May 07 '21 at 22:08
  • @MarioGalic Looks good. If Aviral agrees that this answers the question, I'd propose to close it as duplicate. – Andrey Tyukin May 07 '21 at 22:11
  • I'm not sure this should be tagged [tag:scala-3], since it's not specific to Scala 3. – user May 09 '21 at 14:21

1 Answers1

2

As the Tour Of Scala or the Scala 3 book says

When you create a case class with parameters, the parameters are public vals.

Therefore, in

case class Person(name: String, age: Int)

both name and age will be public, unlike in an ordinary class.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93