Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala's parametric fields and constructor arguments

Tags:

scala

I understand that parametric fields (like x in the example below) behave like normal fields; so you can reference them in methods:

class Test(val x: Int) { // x is a parametric field
  override def toString = "Test: " + x;
}

However, if you drop the keyword val, the code still compiles (and looking and the .class output, x is still a member of the class). So I am wondering, what is the difference between parametric fields (i.e., val x: Int in the above) and constructor arguments (x: Int)?

(With Java in the back of my head, I would have expected the scope of a constructor like x to not include a method like toString.)

like image 395
Hbf Avatar asked Jun 25 '12 12:06

Hbf


1 Answers

Without the val keyword, your code is similar to: class Test (private[this] val x: Int) { ... }. Therefore, xis available in the whole class but not from the outside.

It's not mentioned in your question but it might also be useful: in a case class the default modifier is val. Thus case class Test(x: Int) {...}is equivalent to case class (val x: Int) {...}.

like image 75
Nicolas Avatar answered Oct 10 '22 20:10

Nicolas