5

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.

1 Answer 1

7

But it means that x is stored in the class, which I want to avoid.

If you don't reference constructor argument anywhere except the constructor itself, field won't be created. If you reference x e.g. in toString(), Scala will automatically create and assign private val for you.

Use javap -c -private A to verify what kind of fields are actually created.

BTW you pass this inside a constructor, which means a.derive() gets a reference to possibly non-initialized instance of A. Be careful!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.