开发者

Is it possible to overload constructors in scala?

My question is that if it is possible to 开发者_JAVA百科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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜