具有非实例变量助手的构造函数?

时间:2010-05-22 17:21:43

标签: scala constructor

我有很多类看起来像这样:

class Foo(val:BasicData) extends Bar(val) {
    val helper = new Helper(val)
    val derived1 = helper.getDerived1Value()
    val derived2 = helper.getDerived2Value()
}

...除了我不想在构造函数的末尾之外保留“helper”的实例。在Java中,我会做这样的事情:

public class Foo {
  final Derived derived1, derived2;
  public Foo(BasicData val) {
     super(val);
     Helper helper = new Helper(val);
     derived1 = helper.getDerived1Value();
     derived2 = helper.getDerived2Value();
  }
}

那么我如何在Scala中做类似的事情呢?我知道使用apply方法创建一个与该类同名的辅助对象:我希望稍微简洁一些。

2 个答案:

答案 0 :(得分:5)

您可以使用块来创建临时助手val并返回一个元组,如下所示:

class Foo(v: BasicData) extends Bar(v) {
  val (derived1, derived2) = {
    val helper = new Helper(v)
    (helper.getDerived1Value(), helper.getDerived2Value())
  }
}

答案 1 :(得分:4)

在结束之前,最好先查看javap输出(包括私有成员),这样可以在中间模式匹配中使用Tuple2的任何字段。

从Scala 2.8.0.RC2开始,这个Scala代码(为了编译而充实):

class BasicData
{
  def basic1: Int = 23
  def basic2: String = "boo!"
}

class Helper(v: BasicData)
{
  def derived1: Int = v.basic1 + 19
  def derived2: String = v.basic2 * 2
}

class Bar(val v: BasicData)

class   Foo(v: BasicData)
extends Bar(v)
{
  val (derived1, derived2) = {
    val helper = new Helper(v)
    (helper.derived1, helper.derived2)
  }
}

生成此Foo类:

% javap -private Foo
public class Foo extends Bar implements scala.ScalaObject{
    private final scala.Tuple2 x$1;
    private final int derived1;
    private final java.lang.String derived2;
    public int derived1();
    public java.lang.String derived2();
    public Foo(BasicData);
}