Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare empty list and then add string in scala?

Tags:

scala

I have code like this:

val dm  = List[String]() val dk = List[Map[String,Object]]()  .....  dm.add("text") dk.add(Map("1" -> "ok")) 

but it throws runtime java.lang.UnsupportedOperationException.

I need to declare empty list or empty maps and some where later in the code need to fill them.

like image 296
rjc Avatar asked Jul 02 '11 13:07

rjc


People also ask

How do I create a list string in Scala?

Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.

How do I append 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”.

How do you add an empty object to a list?

You can add elements to an empty list using the methods append() and insert() : append() adds the element to the end of the list. insert() adds the element at the particular index of the list that you choose.


1 Answers

Scala lists are immutable by default. You cannot "add" an element, but you can form a new list by appending the new element in front. Since it is a new list, you need to reassign the reference (so you can't use a val).

var dm  = List[String]() var dk = List[Map[String,AnyRef]]()  .....  dm = "text" :: dm dk = Map(1 -> "ok") :: dk 

The operator :: creates the new list. You can also use the shorter syntax:

dm ::= "text"  dk ::= Map(1 -> "ok") 

NB: In scala don't use the type Object but Any, AnyRef or AnyVal.

like image 64
paradigmatic Avatar answered Oct 01 '22 06:10

paradigmatic