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?
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?
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")
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)