I.e. Is it possible to make a var that is not assignable from outside of the class ?
Can I make "public val" but "private var" in Scala in one line?
5.1k Views Asked by Łukasz Lew At
3
There are 3 best solutions below
0

You certainly make something a var and then make it private to the class defining the field.
scala> class Holder(private var someValue: String) {
| def getValueOfOther(other: Holder) = other.someValue
| def combinedWith(holder: Holder) = new Holder(holder1.someValue + " " + holder2.someValue)
| def value = someValue
| }
defined class Holder
scala> val holder1 = new Holder("foo")
holder1: Holder = Holder@1303368e
scala> val holder2 = new Holder("bar")
holder2: Holder = Holder@1453ecec
scala> holder2.getValueOfOther(holder1)
res5: String = foo
scala> val holder3 = holder1 combinedWith holder2
holder3: Holder = Holder@3e2f1b1a
scala> holder3.value
res6: String = foo bar
Right now, no, there's no way to do that.
You're limited to the following three-line solution:
Now the class itself is the only one who can manipulate the underlying field
xHidden
, while other instances of the class can use the setter method and everyone can see the getter method.If you don't mind using different names, you can just make the var private and forget the setter (two lines).
There's no "var to me, val to them" keyword.