How to declare empty list and then add string in scala?
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 need to mutate stuff, use ArrayBuffer
or LinkedBuffer
instead. However, it would be better to address this statement:
I need to declare empty list or empty maps and some where later in the code need to fill them.
Instead of doing that, fill the list with code that returns the elements. There are many ways of doing that, and I'll give some examples:
// Fill a list with the results of calls to a method
val l = List.fill(50)(scala.util.Random.nextInt)
// Fill a list with the results of calls to a method until you get something different
val l = Stream.continually(scala.util.Random.nextInt).takeWhile(x => x > 0).toList
// Fill a list based on its index
val l = List.tabulate(5)(x => x * 2)
// Fill a list of 10 elements based on computations made on the previous element
val l = List.iterate(1, 10)(x => x * 2)
// Fill a list based on computations made on previous element, until you get something
val l = Stream.iterate(0)(x => x * 2 + 1).takeWhile(x => x < 1000).toList
// Fill list based on input from a file
val l = (for (line <- scala.io.Source.fromFile("filename.txt").getLines) yield line.length).toList
As everyone already mentioned, this is not the best way of using lists in Scala...
scala> val list = scala.collection.mutable.MutableList[String]()
list: scala.collection.mutable.MutableList[String] = MutableList()
scala> list += "hello"
res0: list.type = MutableList(hello)
scala> list += "world"
res1: list.type = MutableList(hello, world)
scala> list mkString " "
res2: String = hello world
As mentioned in an above answer, the Scala List is an immutable collection. You can create an empty list with .empty[A]
. Then you can use a method :+
, +:
or ::
in order to add element to the list.
scala> val strList = List.empty[String]
strList: List[String] = List()
scala> strList:+ "Text"
res3: List[String] = List(Text)
scala> val mapList = List.empty[Map[String, Any]]
mapList: List[Map[String,Any]] = List()
scala> mapList :+ Map("1" -> "ok")
res4: List[Map[String,Any]] = List(Map(1 -> ok))