When I use ArrayBuffer
, I should use:
val arr = new ArrayBuffer[Int]
but when I use Map
, I should use:
val map = Map[Int, Int]()
When I use ArrayBuffer
, I should use:
val arr = new ArrayBuffer[Int]
but when I use Map
, I should use:
val map = Map[Int, Int]()
To understand why you need to use Map[T, T]()
and not new Map[T, T](...)
, you need to understand the how the apply method on a companion object works.
A companion object is an object that has the same name as a class along with it. This object contains, generally, contains factory methods and other methods that you need to create (easily) the objects of the class.
To make sure that one doesn't have to go through a lot of verbose code, Scala makes use of the apply method which is executed directly when you call the object as you would call a function.
So, the companion object of Map
must look something like this:
object Map {
def apply[K, V](...) = new Map[K,V](...) // Or something like this
}
While the class would be something like
protected class Map[K, V](...) {
...
}
Now calling Map[String, String](...)
you are actually calling the apply
method of the Map companion object.
ArrayBuffer
, here, does not have a companion object though. Thus, you need to create a new instance of the class yourself by directly using the constructor.