How do you add an element to a List
in Scala 2.7.5, without creating a new List
and without using a deprecated solution.
You could use a ListBuffer
, which provides constant time append:
val buffer = new scala.collection.mutable.ListBuffer[Int]
buffer += 1
buffer += 2
val list = buffer.toList
It's worth pointing out that List
has a very specific meaning in scala, which is not equivalent to the java.util.List
interface. List
is a sealed, abstract class representing a recursive data-structure which has a head and a tail. (There do exist Java list-like structures in scala, some of which are mutable.)
Scala's List
s are immutable; modifying a list in any way is not possible, although you can create a new list be prepending to an existing one (which gives a new object back). Even though they are immutable, the structure is no more expensive in terms of object creation than, say, appending to a java.util.LinkedList
The +
method has been deprecated for good reason because it is inefficient; instead use:
val newList = theList ::: List(toAppend)
I suppose a different way would be to prepend with 2 reversals:
val newList = (toAppend :: theList.reverse).reverse
I doubt this is any more efficient! In general, if I want append behaviour, I use prepend and then reverse
(at the point of needing to access the list):
val newList = toAppend :: theList
//much later! I need to send the list somewhere...
target ! newList.reverse
Non deprecated way of appending an element to a List in Scala 2.7.5?
That does not exist, and it will never exist.
How do you add an element to a List in Scala 2.7.5, without creating a new List and without using a deprecated solution.
Use ::
:
val newList = element :: oldList
Or, if list
is a var
,
list ::= element
It does not create a new List
(though, it creates a new ::
, also known as cons), and it adds an element to it.
If you want to append elements to a sequence without creating a new sequence, use a mutable data structure.
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