This is an important part of the Scala learning curve – dealing with Collections.
This is the quick and easy method for Java developers. The ‘Scala way’ is long winded and I will cover in another post.
For now, if you want to add to a list the easiest way is to use a ListBuffer, as I demonstrate here:
import scala.collection.mutable.ListBuffer . object AddToList extends App { val listBuffer = ListBuffer[String]() listBuffer += "john" listBuffer += "paul" listBuffer += "george" listBuffer += "ringo" listBuffer.foreach { name => { println("My name is " + name) }} }
Why? Because the out-of-the-box List in scala is immutable – you cannot add to it, and that is the scala way. So how to add to an immutable list? I’ll cover that soon.