How to start a List of tuples and add an item to scala

why is this NOT permissible?

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

Basically, I want to initialize a list of tuples and add a tuple to the list.

+4
source share
2 answers

Here you have two errors.

First, you are trying to create an instance of List, which is an abstract class

I believe that you are trying to do the following

var a : List[(String,String)] = List()

This will create a list of empty list of tuples.

Secondly, you are trying to add an element that is not really a tuple, so I believe you should try the following

 a = a:+(("x","y"))

Here you define tuples and add them to your list a

+6
source

You can create an empty one in List[(String, String)]various 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

, Traversable, Iterable, Seq LinearSeq a List, (, Seq.empty[(String, String)]).

, :+:

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

cons ::, . Scala , :, :

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

, , , , :

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

, , , , , :

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

( , ).

+4
source

All Articles