Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't append to scala's mutable LinkedList?

I'm looking at the API and the :+ method returns a new LinkedList. The append method will only allow the appending of another linked list. The += method needs a var to work. Why would anyone ever need these if the LinkedList is mutable? What craziness is this?

If I had something like this in Java

final LinkedList myList = new LinkedList<String>();
mylist.add("balh");

How do I achieve the same thing in Scala?

like image 495
dpington Avatar asked Nov 09 '11 05:11

dpington


3 Answers

If append can only take a LinkedList then why not use

mylist append LinkedList("something")

or

mylist append LinkedList(otherContainer: _*)

There is a reason for allowing only other LinkedLists in append, I think, because this guarantees the following:

l1 = LinkedList(1, 2, 3)
l2 = LinkedList(4)
l3 = LinkedList(5)

l1 append l2
// l1 == LinkedList(1, 2, 3, 4)
// l2 == LinkedList(4)

l2 append l3
// l1 == LinkedList(1, 2, 3, 4, 5)
// l2 == LinkedList(4, 5)
// l3 == LinkedList(5)
like image 131
Debilski Avatar answered Nov 18 '22 23:11

Debilski


You can use a Buffer to build your values and convert it in the data structure using mapResult.

//Create a buffer which will build a linked list
val buf = new ArrayBuffer[String]  mapResult { xs => LinkedList( xs:_* ) }

//You can append elements with +=, it is overriden to allow its use on a val
buf += "Something"
buf += "else"

//At the end you get your list
val lst = buf.result

// lst ==  LinkedList(Something, else) 
like image 28
paradigmatic Avatar answered Nov 19 '22 01:11

paradigmatic


Mutability is on the actual elements within the list and not on the structure that the list has (persistence). This is also stated in the scaladoc.

If returning a new List each time is not what you are after, and you cannot use var, you could always use the Java LinkedList.

val mylist = new java.util.LinkedList[String]
mylist add "something"

I'd stick with the Scala lists, if at all possible.

like image 3
gpampara Avatar answered Nov 19 '22 00:11

gpampara