Aviral Srivastava
Aviral Srivastava

Reputation: 4582

Are constructor parameters treated differently in classes vs. case classes?

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?

Upvotes: 0

Views: 128

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44957

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.

Upvotes: 2

Related Questions