Is it possible to overload constructors in scala?

My question is, if you can overload constructors in scala?

So I can write code like:

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

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

+3
source share
3 answers

, . Scala , "". , . "" , . Java . , args .

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")
+9

, " " , ( ). , . ( "" ):

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

, , (, )

+5
class MyCons{    

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

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

}   

, .

0

Source: https://habr.com/ru/post/1766537/


All Articles