In Scala, can I use the same name for arguments and class fields

advertisements

In Java I usually call the argument of the setter with the same name as the field

public void setA(int a){
    this.a = a;
}

The reason is that later the IDE will show a as the param name, so it's better documented.

How do I do the same in Scala?


You don't have to. When you create a Scala class:

class A(val a: Int)

You get an accessor for 'free'. If you declare the argument as a var you get a setter as well. So, to answer your question: arguments already are class fields.

val myA = new A(42)
myA.a  // 42

class B(var b: Int)
val myB = new B(42)
myB.b  // 42
myB.b = 43
myB.b  // 43

The getXXX / setXXX convention of the java beans does not apply to Scala (which is sometimes an issue when trying to use a Java library in Scala).