why this is NOT valid?
var a = List[(String,String)]
a = a :: ("x","y")
basically i want to init a list of tuple and add a tuple to the list.
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”.
In scala we can append elements to the List object in one way only and that is while initializing of the object. This is because the List object is immutable in scala so we cannot change its value once we assign the object. But we have implementation of List by ListBuffer and so many classes.
In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method. A tuple with two elements can be created as follows: Scala 2 and 3.
Thankfully, Scala already has a built-in tuple type, which is an immutable data structure that we can use for holding up to 22 elements with different types.
Here you have two mistakes.
The first one is that you are trying to instantiate List which an abstract class
I believe that what you are trying to do is the following
var a : List[(String,String)] = List()
This will create a list of an empty list of tuples.
The second is that you are trying to add an element which is not actually a tuple so I believe that you should try the following
a = a:+(("x","y"))
Here you are defining a tuples and adding it to your List a
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