Scala problem optional constructor

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() } } 

Result

 null null 

I want to be

 calling elvis null 

How to achieve this? I cannot call the testMethod method after creating the object.

Ointments

+7
source share
1 answer

Your test method is first called in the main constructor. There is no other way that another constructor can avoid calling it before running its own code.

In your case, you should simply undo which constructor does something. The main constructor has a string parameter, and an auxiliary parameter for it. Added gain, you can declare 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 more flexible, usually assigning each field from a parameter. Scala syntax makes that very easy. You can make this main constructor private if required.

Edit : even easier with default setting

 class Constructor(var s: String = null) { def testMethod = println(s) testMethod } 
+19
source

All Articles