Scala:使用备用构造函数分配类属性

时间:2018-05-21 18:56:32

标签: scala class constructor

我有一个带有由构造函数填充的属性的类,但我需要在调用备用构造函数时以不同的方式填充它。例如。我希望代码是这样的:

class MyClass(someArg: String) {
  val someValue = valuePopulator(someArg)

  def this(someArg1: String, someArg2: String) {
    someValue = alternateValuePopulator(someArg1, someArg2)
  }
  def valuePopulator(arg: String) {
  \\ does something
  }
  def alternateValuePopulator(arg: String, arg2: String) {
  \\ does something else
  }
}

当然,这不起作用,但基本上我希望someValue在正常构造类时等于valuePopulator的输出。但是,someValue应该是调用备用构造函数时alternateValuePopulator的结果。如何创建由构造函数填充的类属性,其方式取决于调用哪个构造函数?

1 个答案:

答案 0 :(得分:3)

两个构造函数之间的共同点似乎是直接接受someValue的主要构造函数:

class MyClass private (val someValue: SomeValueType) {

  def this(someArg: String) {
    this(valuePopulator(someArg))
  }

  def this(someArg1: String, someArg2: String): SomeValueType = {
    this(alternateValuePopulator(someArg1, someArg2))
  }

  def valuePopulator(arg: String) {
  \\ does something
  }
  def alternateValuePopulator(arg: String, arg2: String): SomeValueType = {
  \\ does something else
  }
}