In Scala, if we have
class Foo(bar:String)
We can create a new object but cannot access bar
val foo = new Foo("Hello")
foo.bar // gives error
However, if we declare Foo to be a case class this works:
case class Foo(bar:String)
val foo = Foo("hello")
foo.bar // works
I am forced to make many of my classes as case classes because of this. Otherwise, I have to write boilerplate code for accessing bar:
class Foo(bar:String) {
val getbar = bar
}
So my questions are:
- Is there any way to “fix” this without using case classes or boilerplate code?
- Is using case classes in this context a good idea? (or what are the disadvantages of case classes?)
I guess the second one deserves a separate question.
Just use val keyword in constructor to make it publicly accessible:
As for your question: if this is the only feature you need, don’t use case classes, just write with
val.However, would be great to know why case classes are not good.
In case classes all arguments by default are public, whereas in plain class they’re all private. But you may tune this behaviour:
And even like that:
For case classes (thanks to @JamesIry):