6

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..

Community
  • 1
  • 1
Clive
  • 3,991
  • 3
  • 17
  • 15

1 Answers1

15

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.

huynhjl
  • 41,520
  • 14
  • 105
  • 158