Sunday 28 June 2015

Appending an element to a List

In scala, List is immutable. To mutate lists one has to operate on a temporary ListBuffer object.
import scala.collection.mutable.ListBuffer

object ListExample {
  def main(args: Array[String]): Unit = {
    var lb = new ListBuffer[Int]()
    lb += (1, 2, 3, 4, 5)
    lb.remove(2)
    println(lb.toList)
  }  
}
NOTE: ListBuffer implements List interface but does not respond to its methods (e.g. reverse, drop)

No comments:

Post a Comment