Can I pass arguments to Scala class constructor that are not stored into class itself?
I want to achieve functionality which in Java could be written as follows:
class A {
private final SomethingElse y;
public A(Something x) {
y = x.derive(this);
}
}
I.e. class constructor takes parameter that is later transformed to another value using reference to this. The parameter is forgotten after constructor returns.
In Scala I can do:
class A(x: Something) {
val y = x.derive(this)
}
But it means that x is stored in the class, which I want to avoid. Since x.derive method uses reference to this, I can not make the transformation in companion object.
If you don’t reference constructor argument anywhere except the constructor itself, field won’t be created. If you reference
xe.g. intoString(), Scala will automatically create and assign privatevalfor you.Use
javap -c -private Ato verify what kind of fields are actually created.BTW you pass
thisinside a constructor, which meansa.derive()gets a reference to possibly non-initialized instance ofA. Be careful!