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?
, . 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")
, " " , ( ). , . ( "" ):
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")
, , (, )
class MyCons{ def this(msg:String){ this() println(msg) } def this(msg1:String , msg2:String){ this() println(msg1 +" "+msg2) } }
, .
Source: https://habr.com/ru/post/1766537/More articles:Renaming a large number of CouchDb - couchdbEmbed error handling in my infrastructure - phpIs there anything better than NSTimer when time is absolutely important? - iphoneNo xdebug in phpinfo () - phpBenchmarking math.h square root and square root Quake - c ++The random number generator does not work - cinput.setAttribute ('type', 'checkbox'); IE Error - javascriptHow to calculate Lucas Numbers in Java - javaExclude link restriction exception from SQL in C # - c #Протокол управления кофе-транспортом Hyper Text - browserAll Articles