想象一下这段简单的代码:
class Constructor() {
var string: String = _
def this(s: String) = {this() ; string = s;}
def testMethod() {
println(string)
}
testMethod
}
object Appl {
def main(args: Array[String]): Unit = {
var constructor = new Constructor("calling elvis")
constructor = new Constructor()
}
}
结果是
null
null
我想成为
calling elvis
null
如何实现这一目标?我无法在对象创建后调用方法 testMethod 。
Mazi
首先在主构造函数中调用您的测试方法。另一个构造函数无法在其自己的代码运行之前避免调用它。
在您的情况下,您应该简单地反转哪个构造函数执行什么操作。让主构造函数具有字符串参数,辅助构造函数将其设置为 null。添加增益,可以直接在参数列表中声明var。
class Constructor(var s: String) {
def this() = this(null)
def testMethod() = println(s)
testMethod()
}
一般来说,主构造函数应该更灵活,通常从参数分配每个字段。 Scala 语法使这一切变得非常简单。如果需要,您可以将该主构造函数设为私有。
Edit:使用默认参数仍然更简单
class Constructor(var s: String = null) {
def testMethod = println(s)
testMethod
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)