What the difference between List.empty
, List()
and new List()
? When should I use which?
An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.
Actually, it will not create a new ArrayList in memory, instead it will replace the old list.
list is a global name that may be overridden during runtime. list() calls that name. [] is always a list literal.
The emptyList() method of Java Collections returns the list with no elements. This method is immutable.
First of all, new List()
won't work, since the List
class is abstract. The other two options are defined as follows in the List
object:
override def empty[A]: List[A] = Nil override def apply[A](xs: A*): List[A] = xs.toList
I.e., they're essentially equivalent, so it's mostly a matter of style. I prefer to use empty
because I find it clearer, and it cuts down on parentheses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With