Che differenza c'è tra List.empty
, List()
e new List()
? Quando dovrei usare quale?List.empty vs. List() vs. new List()
24
A
risposta
30
Prima di tutto, new List()
non funziona, poiché la classe List
è astratta. Le altre due opzioni sono definite come segue in the List
object:
override def empty[A]: List[A] = Nil
override def apply[A](xs: A*): List[A] = xs.toList
Vale a dire, sono sostanzialmente equivalenti, quindi è soprattutto una questione di stile. Preferisco usare empty
perché lo trovo più chiaro e riduce le parentesi.
12
dal codice sorgente di List abbiamo:
object List extends SeqFactory[List] {
...
override def empty[A]: List[A] = Nil
override def apply[A](xs: A*): List[A] = xs.toList
...
}
case object Nil extends List[Nothing] {...}
modo che possiamo vedere che è esattamente la stessa
Per completezza, si può anche utilizzare Nil
.
4
Per le creazioni di una lista vuota, come altri hanno detto, è possibile utilizzare quello che ti sembra più adatto.
Tuttavia, per il pattern matching contro un elenco vuoto, è possibile utilizzare solo Nil
scala> List()
res1: List[Nothing] = List()
scala> res1 match {
| case Nil => "empty"
| case head::_ => "head is " + head
| }
res2: java.lang.String = empty
EDIT: Correzione: case List()
funziona anche, ma case List.empty
non compila
Problemi correlati
- 1. List + = Tuple vs List = Lista + Tuple
- 2. Clojure list vs. vector vs. set
- 3. Array vs List a Elm
- 4. String vs appartenenza check list
- 5. List vs Map in Java
- 6. Polymorphism: Perché utilizzare "List list = new ArrayList" anziché "ArrayList list = new ArrayList"?
- 7. Haskell map/zip vs. list comprehension
- 8. std :: list vs std :: vector iteration
- 9. Elenco Python() vs list building building speed
- 10. python: confronto tra prestazioni deque vs list
- 11. IEnumerable vs List nella classe Response, ServiceStack
- 12. Lists.newArrayList vs new ArrayList
- 13. Allocazione memoria Windows vs. Linux/std :: list performance costruttore
- 14. Comportamento di shuffle su Set vs List utilizzando scala.util.Random
- 15. List comprehension e len() vs. simple for loop
- 16. Cos'è la tupla? E tuple contro List vs. Vector?
- 17. Metodo Python sort() sulla funzione list vs builtin sort()
- 18. const vs new const
- 19. AS3 {} vs new Object
- 20. newInstance() vs new
- 21. Bind List a DataSource
- 22. Differenza tra List e Array
- 23. subclass.prototype = new superclasse() vs. sottoclasse = new superclasse()
- 24. Quale implementazione di List utilizzare?
- 25. CoffeeScript “Array()” vs “new Array()”
- 26. + = new EventHandler (Method) vs + = Metodo
- 27. new DateTime() vs default (DateTime)
- 28. Highcharts - redraw() vs. new Highcharts.chart
- 29. Qual è la differenza quando si restituisce IList vs List o IEnumerable vs List <Class>. Voglio sapere quale è meglio restituire
- 30. GWT List Editor vincolante
È possibile aggiungere 'quelle negative per quella lista. – Jesper