Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is new required in scala [duplicate]

Possible Duplicate:
“new” keyword in Scala

Ive noticed that creating certain instances in Scala you can leave off using new. When is it required that a developer use new? And why do some objects allow you to miss off using it?

Thanks

List("this","is","a","list") creates a List of those four strings; no new required

Map("foo" -> 45, "bar" ->76) creates a Map of String to Int, no new required and no clumsy helper class.

Taken from here..

like image 930
Clive Avatar asked Mar 19 '12 01:03

Clive


1 Answers

In general the scala collection classes define factory methods in their companion object using the apply method. The List("this","is","a","list") and Map("foo" -> 45, "bar" ->76) are syntactic sugar for calling those apply methods. Using this convention is fairly idiomatic scala.

In addition if you define a case class C(i: Int) it also defines a factory C.apply(i: Int) method which can be called as C(i). So no new needed.

Other than that, the new is required to create objects.

like image 141
huynhjl Avatar answered Oct 02 '22 17:10

huynhjl