我有一个带有由构造函数填充的属性的类,但我需要在调用备用构造函数时以不同的方式填充它。例如。我希望代码是这样的:
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
的结果。如何创建由构造函数填充的类属性,其方式取决于调用哪个构造函数?
答案 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
}
}