class A (names: String*) {
val namesBuffer: ListBuffer[String] = new ListBuffer[String]
}
I was wondering, how I can add the names of the names array from the primary constructor argument to the namesBuffer field when creating the object ?
Do I have to create an auxiliary construtor to do so or is there another way to tell Scala to do operations in the primary Constructor ?
Note: The example above is fictive, I just want to know, how I can tell the primary constructor to do some more operations than assigning fields.
As axel22’s answer demonstrates, you can perform those operations anywhere in the body of the class.
But it is good practice IMO to initialize the field fully with a single expression.
When side effects are required, you can achieve this using curly braces to make a block, which is an expression having the value of the last line:
With this technique, you ensure that no other initialization logic accesses the value of
namesBufferbefore you have finished initializing that.