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
You define auxiliary Scala class constructors by defining methods that are named this . There are only a few rules to know: Each auxiliary constructor must have a different signature (different parameter lists) Each constructor must call one of the previously defined constructors.
Constructors in Scala describe special methods used to initialize objects. When an object of that class needs to be created, it calls the constructor of the class. It can be used to set initial or default values for object attributes.
Abstract class cannot have a constructor.
When you define a subclass in Scala, you control the superclass constructor that's called by its primary constructor when you define the extends portion of the subclass declaration.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With