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
.)
Without the val
keyword, your code is similar to: class Test (private[this] val x: Int) { ... }
. Therefore, x
is 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) {...}
.
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