Reputation: 4463
Imagine this simple piece of code:
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()
}
}
The result is
null
null
I would like to be
calling elvis
null
How to achieve this? I cannot call the method testMethod after the object creation.
Mazi
Upvotes: 7
Views: 2520
Reputation: 29528
Your test method is called in the main constructor first thing. There is no way another constructor might avoid it being called before its own code runs.
In your case, you should simply reverse which constructor does what. Have the main constructor have the string parameter, and the auxiliary one set it to null. Added gain, you can declare the var directly in the parameter list.
class Constructor(var s: String) {
def this() = this(null)
def testMethod() = println(s)
testMethod()
}
In general, the main constructor should be the more flexible one, typically assigning each field from a parameter. Scala syntax makes doing exactly that very easy. You can make that main constructor private if need be.
Edit: still simpler with default parameter
class Constructor(var s: String = null) {
def testMethod = println(s)
testMethod
}
Upvotes: 19