Search code examples
scalascala-collectionsmutable

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?


Solution

  • 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)