Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make "public val" but "private var" in Scala in one line?

I.e. Is it possible to make a var that is not assignable from outside of the class ?

like image 656
Łukasz Lew Avatar asked Feb 14 '11 00:02

Łukasz Lew


People also ask

Can you change a Val in Scala?

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.

What is the difference between a VAR a Val and DEF in Scala?

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)


1 Answers

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.

like image 55
Rex Kerr Avatar answered Nov 14 '22 15:11

Rex Kerr