ArrayBuffer[Int]() vs new ArrayBuffer[Int]()

what is the difference between
val x = ArrayBuffer[Int]()
val x = new ArrayBuffer[Int]()

If there is technically no difference, why can I use both?

Thank you…

Let me add one more to that


But the companion object apply semantics also gives you varargs, so you could do:


They accomplish the same thing in different ways.

new ArrayBuffer[Int]() calls the constructor, which creates a new, empty array buffer. That constructor takes no parameters.

ArrayBuffer[Int]() is shorthand for ArrayBuffer.apply[Int](). that’s a method on the companion object that takes a variable number of elements, and initialized the buffer with those values. You pass no elements, so the buffer is created empty.

Extra care for ArrayBuffer(5) vs new ArrayBuffer(5): The first one calls ArrayBuffer.apply[A](as: A*), and desugars to ArrayBuffer.apply[Int](Seq(5)), creating a new ArrayBuffer populated by the single Int 5. The second one initializes a new, empty ArrayBuffer with an initial capacity of 5

1 Like