Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non deprecated way of appending an element to a List in Scala 2.7.5?

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.

like image 519
Geo Avatar asked Feb 08 '10 13:02

Geo


3 Answers

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
like image 166
Fabian Steeg Avatar answered Oct 03 '22 22:10

Fabian Steeg


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 Lists 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
like image 37
oxbow_lakes Avatar answered Oct 03 '22 23:10

oxbow_lakes


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.

like image 45
Daniel C. Sobral Avatar answered Oct 03 '22 22:10

Daniel C. Sobral