I'm new to scala and would like to use class parameters to assign the value to a field of the same. In Java, we do similar thing within a constructor:
public class Test{
private final int value;
public Test(int value){
this.value = value;
}
}
Now, I tried to do a similar thing in Scala
:
class Test(value: Int){
val value = ..WHAT..value //Is there a way to assign a parameter value to a field with the same name?
}
object Test{
def testMethod = //access value and do something with it.
}
Can we do something similar to what we can in do in Java?
Scala provides a shorter syntax for creating such a member - just add the keyword
val
before the argument name in the class parameter list. You can also add a modifier (e.g.private
):If you don't like exposing a private member, you could go for this:
Which would you give you a getter and setter, both accessible by calling
quote
.