Add to a List in Scala – easy way

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s