Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending an element to the end of a list in Scala

Tags:

arrays

scala

I can't add an element of type T into a list List[T]. I tried with myList ::= myElement but it seems it creates a strange object and accessing to myList.last always returns the first element that was put inside the list. How can I solve this problem?

like image 398
Masiar Avatar asked Oct 17 '11 12:10

Masiar


People also ask

How do I append to a list in Scala?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.

Which method is used for adding an element at the end of the list?

There are two methods to add elements to the list. add(E e): appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created. add(int index, E element): inserts the element at the given index.

How do you add an element to an array in Scala?

Use the concat() Method to Append Elements to an Array in Scala. Use the concat() function to combine two or more arrays. This approach creates a new array rather than altering the current ones. In the concat() method, we can pass more than one array as arguments.


Video Answer


1 Answers

List(1,2,3) :+ 4  Results in List[Int] = List(1, 2, 3, 4) 

Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).

like image 62
Landei Avatar answered Oct 22 '22 16:10

Landei