3

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]()
nbro
  • 15,395
  • 32
  • 113
  • 196
user2848932
  • 776
  • 1
  • 14
  • 28
  • 1
    Check out the answers on these existing questions for some more explanation: http://stackoverflow.com/questions/9727637/new-keyword-in-scala, http://stackoverflow.com/questions/9737352/what-is-the-apply-function-in-scala – mikej Mar 17 '15 at 11:37

1 Answers1

5

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.

Chetan Bhasin
  • 3,503
  • 1
  • 23
  • 36
  • 2
    There is a companion object for `ArrayBuffer`: [ScalaDoc](http://www.scala-lang.org/api/2.11.5/index.html#scala.collection.mutable.ArrayBuffer$@apply[A](elems:A*):CC[A]) – mikej Mar 17 '15 at 19:05