Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala class constructor local parameters

Tags:

scala

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.

like image 544
st33v3 Avatar asked Oct 19 '12 11:10

st33v3


1 Answers

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!

like image 68
Tomasz Nurkiewicz Avatar answered Oct 21 '22 13:10

Tomasz Nurkiewicz