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?
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”.
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.
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.
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).
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