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.
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.
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”.
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.
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
.
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