override - Is it possible to overload constructors in scala? -


My question is if it is possible to overload the constructor in Scala?

Then I can write code like:

  var = new Foo (1) var = new Foo ("bar")  
< P> And if this is not possible, is there any equivalent tricks?

Sure, but there are restrictions in Scala that one of your consultants is "primary". Next to the Primary Constructor, there are special, convenient syntax for the consignor to be installed after the name of the class. Other "secondary" constructors can also be defined, but they need to call the primary constructor. It is different from Java, and some more restrictive. This is done so that the constructor algens can be treated as fields.

Your example looks like

  class Foo (myArg: String) {// primary constructor def (myIntArg: int) = this (myIntArg.toString) // Secondary constructor} val x = new foo (1) val y = new foo ("bar")  

Comments