简体   繁体   中英

Scala class constructor local parameters

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);
    }
}

Ie 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.

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 eg 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM