Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 558
Massimo Ugues Avatar asked Aug 26 '11 10:08

Massimo Ugues


People also ask

How does Scala define auxiliary constructor?

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.

Can Scala object have constructor?

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.

Which of the following Cannot have a constructor Scala?

Abstract class cannot have a constructor.

How do I call a super constructor in Scala?

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.


1 Answers

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
}
like image 183
Didier Dupont Avatar answered Oct 09 '22 22:10

Didier Dupont