I.e. Is it possible to make a var that is not assignable from outside of the class ?
In short: No, you cannot. This is the point of immutability, ensuring that you can always be sure that the value stays the same. This is why there's an option of immutables [vals] and mutables [vars] it's flexible and allows you to choose depending on your needs.
There are three ways of defining things in Scala: def defines a method. val defines a fixed value (which cannot be modified) var defines a variable (which can be modified)
Right now, no, there's no way to do that.
You're limited to the following three-line solution:
class Hider {
private[this] var xHidden: Int = 0
def x = xHidden
private def x_=(x0: Int) { xHidden = x0 }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With