Question

We create a new map in scala using:

val treasureMap = Map[Int, String]()

But why is it illegal to use the new operator here?

val treasureMap = new Map[Int, String]()

I thought new is for creating new object and in the example above I AM creating a new object.

Was it helpful?

Solution

Map is a trait (like an interface in java) - it's a contract without implementation.

Without new you are using factory method apply of singleton object named Map:

val treasureMap = Map.apply[Int, String]()

In scala you could call an apply method of any object by placing brackets after object name:

val functionIncrement = (_: Int) + 1

functionIncrement(2)
// 3

functionIncrement.apply(2)
// 3

val treasureMap = Map.apply(1 -> "a")

treasureMap(1)
// a

treasureMap.apply(1)
// a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top