matanox
matanox

Reputation: 13686

Can a Scala case class exclude setters?

Can a Scala case class exclude setters, e.g. that:

case class Foo (foo: String, bar: Integer)

would encapsulate a named String and Integer, and keep them immutable from the outside.

Or, equivalently, can you create a body-less class that has input arguments and getters for them, in one unceremonial line of code?

Upvotes: 2

Views: 1536

Answers (1)

Electric Coffee
Electric Coffee

Reputation: 12104

All classes by default are free of setters in Scala, unless stated explicitly, even case classes. foo and bar are both vals, not vars (in the vein of data immutability in the world of functional programming), so case classes already lack setters, as desired.

Watch:

scala> case class Foo(foo: String, bar: Integer)
defined class Foo

scala> val a = Foo("hello", 12)
a: Foo = Foo(hello,12)

scala> a.foo = "meh"
<console>:10: error: reassignment to val
       a.foo = "meh"
             ^

scala> case class MutableFoo(var foo: String, var bar: Integer)
defined class MutableFoo

scala> val b = MutableFoo("hello", 21)
b: MutableFoo = MutableFoo(hello,21)

scala> b.foo = "bleh"
b.foo: String = bleh

scala> b
res10: MutableFoo = MutableFoo(bleh,21)

As for creating a class with getters that isn't a case class, sure, that's easy too:

scala> class Bar(val foo: String, val bar: Int)
defined class Bar

scala> val c = new Bar("hi", 22)
c: Bar = Bar@43c89f32

scala> c.foo
res11: String = hi

scala> c.bar
res12: Int = 22

Here you just need to explicitly put val in the constructor args to tell the compiler you want to make public fields, rather than private ones, of course this works with var too like before

Upvotes: 13

Related Questions