1

When declaring a class in Scala, you can define the parameters as val, like this:

class MathOperations(val _x: Int, val _y: Int) {
  var x: Int = _x
  var y: Int = _y

  def product = x*y
}

But in this case, when I leave out the val keyword, an instance of the class behaves exactly the same (as far as I can figure out)

What is the difference between declaring the parameters as I did above, and doing it without val, like this:

class MathOperations(_x: Int, _y: Int) {
Marco Prins
  • 7,189
  • 11
  • 41
  • 76
  • It's duplicated to at least one question ever posted. Here is a brief answer. If you do not define them as `val`, then they do not become members of the class. However, if the class is `case`, every argument becomes a member of the class. – Ryoichiro Oka Oct 31 '14 at 09:29

1 Answers1

3

If you omit the val you will only be able to access _x and _y within class instance as closure on constructor args (in other words they won't be a members of a class MathOperations).

I.e. code like this:

val mo = new MathOperations(1, 2)
mo._x

... will yield compile error, while if you add val it will compile fine.

Eugene Loy
  • 12,224
  • 8
  • 53
  • 79