Zifei Tong
Zifei Tong

Reputation: 1727

Is it possible to overload constructors in scala?

My question is that if it is possible to overload constructors in scala?

So I can write code like:

var = new Foo(1)
var = new Foo("bar")

And if it is not possible, are there any equivalent tricks?

Upvotes: 4

Views: 5936

Answers (3)

Mamunar Rashid
Mamunar Rashid

Reputation: 11

class MyCons{    

  def this(msg:String){    
        this()    
        println(msg)   
  }       

  def this(msg1:String , msg2:String){    
        this()    
        println(msg1 +" "+msg2)    
  }    

}   

For other auxiliary constructor we must need to call primary constructor or other auxiliary defined earlier.

Upvotes: 1

Landei
Landei

Reputation: 54574

As you can see in Dave Griffith's example, the primary constructor must be the "most general" one in the sense that any other constructor must call it (directly and indirectly). As you can imagine, this leads sometimes to ugly primary constructors. A common strategy is to use the companion object to hide the ugliness (and you don't need to type the "new"):

class Foo private (arg:Either[String, Int]){ 
   ...
}

object Foo {
   def apply(arg:String) = new Foo(Left(arg))
   def apply(arg:Int) = new Foo(Right(arg))  
}

val a = Foo(42)
val b = Foo("answer")

Of course you must be careful if you want to inherit from your class (e.g. this isn't possible in the example above)

Upvotes: 7

Dave Griffith
Dave Griffith

Reputation: 20515

Sure, but there are restrictions. Scala requires that one of your constructors be "primary". The primary constructor has the special, convenient syntax of putting the constructor args right after the class name. Other "secondary" constructors may also be defined, but they need to call the primary constructor. This is different than Java, and somewhat more restrictive. It is done this way so that constructor args can be treated as fields.

Your example would look like

class Foo(myArg:String){ //primary constructor
   def this(myIntArg:Int) = this(myIntArg.toString) //secondary constructor
}

val x = new Foo(1)
val y = new Foo("bar")

Upvotes: 10

Related Questions