Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 911
Zifei Tong Avatar asked Dec 03 '22 11:12

Zifei Tong


2 Answers

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")
like image 160
Dave Griffith Avatar answered Jan 13 '23 13:01

Dave Griffith


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)

like image 36
Landei Avatar answered Jan 13 '23 12:01

Landei