How to init List of tuple and add item in scala

You could also write the add like this if you want to add to an existing Array :

var a : List[(String,String)] = List()
a:+=(("x","y"))

You can instantiate an empty List[(String, String)] in many ways:

val list = List[(String, String)]()
val list = List.empty[(String, String)]
val list : List[(String, String)] = Nil
val list : List[(String, String)] = List()
val list = Nil : List[(String, String)]
val list : List[(String, String)] = List.empty

Note, too, that the default instantiations of Traversable, Iterable, Seq, and LinearSeq all also return a List, so you can use those too, (e.g. Seq.empty[(String, String)]).

And then you can add elements using :+:

val newList = list :+ ("x", "y")
val newList = list :+ ("x" -> "y")

You were using the cons method ::, which is used for prepending. In Scala, methods that end in : are right associative:

val newList = ("x" -> "y") :: list

You can also call them using the regular dot syntax if you want them to be left associative, like normal methods:

val newList = list.::("x" -> "y")

The reason this method is right associative is because it prepends elements, allowing you to do things like:

val newList = ("x" -> "y") :: ("a" -> "b") :: list

and retain the expected order (the same order that it appears in the code).


Simple straight way in declaration:

val l=List("type"->"number","min"->"2","step"->"1","value"->"2")

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

Tags:

Scala