简体   繁体   English

Scala类构造函数的本地参数

[英]Scala class constructor local parameters

Can I pass arguments to Scala class constructor that are not stored into class itself? 我可以将参数传递给没有存储到类本身的Scala类构造函数吗? I want to achieve functionality which in Java could be written as follows: 我希望实现Java中的功能,如下所示:

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 . 即类构造函数采用稍后变换为使用参考另一值参数this The parameter is forgotten after constructor returns. 构造函数返回后,该参数被遗忘。

In Scala I can do: 在Scala中我可以做到:

class A(x: Something) {
    val y = x.derive(this)
}

But it means that x is stored in the class, which I want to avoid. 但这意味着x存储在类中,我想避免。 Since x.derive method uses reference to this , I can not make the transformation in companion object. 由于x.derive方法使用了this引用,我无法在伴随对象中进行转换。

But it means that x is stored in the class, which I want to avoid. 但这意味着x存储在类中,我想避免。

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. 如果您在toString()引用x ,Scala将自动为您创建并分配私有val

Use javap -c -private A to verify what kind of fields are actually created. 使用javap -c -private A来验证实际创建的字段类型。

BTW you pass this inside a constructor, which means a.derive() gets a reference to possibly non-initialized instance of A . 顺便说一句,你在构造函数中传递this ,这意味着a.derive()获取对可能未初始化的A实例的引用。 Be careful! 小心!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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