Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.empty vs. List() vs. new List()

What the difference between List.empty, List() and new List()? When should I use which?

like image 659
fredoverflow Avatar asked Mar 13 '12 14:03

fredoverflow


People also ask

What is the difference between an empty list and a null list?

An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.

Does list clear create a new list?

Actually, it will not create a new ArrayList in memory, instead it will replace the old list.

Is list same as []?

list is a global name that may be overridden during runtime. list() calls that name. [] is always a list literal.

What is an empty list in Java?

The emptyList() method of Java Collections returns the list with no elements. This method is immutable.


1 Answers

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.

like image 52
Travis Brown Avatar answered Oct 02 '22 08:10

Travis Brown