scalavaraccess-modifierscase-class

Scala case class: Is public var member possible?


Scala noob here, but while learning about case classes, I see the members are by default read-only. However, if you add var, they become private; and there is no public access modifier. Any way to have a case class with a public var that you can therefore modify directly? I know this may not be what a case class is intended for, but I am wondering nonetheless (since having a var member itself is possible).


Solution

  • I think you might be drawn to a wrong conclusion by Scala's syntax: the fact that you don't have a public qualifier is because public is the default in Scala and you explicitly have to opt out with private or some scoped variation.

    The following code demonstrates that a var in a case class is accessible and works as expected:

    case class Foo(var mutable: Int)
    
    val foo = Foo(42)
    
    foo.mutable = 47
    
    assert(foo == Foo(47))
    

    You can play around with this code here on Scastie.

    Note that if you explicit make the mutable field explicitly private, the code no longer compiles:

    case class Foo(private var mutable: Int)
    
    val foo = Foo(42)
    
    foo.mutable = 47
    
    assert(foo == Foo(47))
    

    The code above will cause the following compile-time error: variable mutable cannot be accessed as a member of ... (again, you can see that in action here).


    With that said, case classes are usually meant to represent immutable data. In doing so, they introduce some synthetic method that you probably won't need or might get in the way (e.g. the copy method). If you want to represent mutable data, you might want to see if a simple class might represent a better fit for your use case.