Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to init List of tuple and add item in scala

Tags:

scala

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.

like image 509
whb Avatar asked Mar 19 '15 10:03

whb


People also ask

How do I add an item 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”.

Can we add elements to list in Scala?

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.

What is Tuple2 in Scala?

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.

Can we have variables of different types inside of a tuple Scala?

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.


1 Answers

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

like image 78
eliasah Avatar answered Oct 02 '22 14:10

eliasah