Scala provides a data structure, the ListBuffer, which is more efficient than List while adding/removing elements in a list. It provides methods to prepend, append elements to a list.
The following is the syntax for declaring an ListBuffer variable.
var z = ListBuffer[String]()
Here, z is declared as an list-buffer of Strings which is initially empty. Values can be added by using commands like the following −
z += "Zara"; z += "Nuha"; z += "Ayan";
Below is an example program of showing how to create, initialize and process ListBuffer −
import scala.collection.mutable.ListBuffer object Demo { def main(args: Array[String]) = { var myList = ListBuffer("Zara","Nuha","Ayan") println(myList); // Add an element myList += "Welcome"; // Add two element myList += ("To", "Howcodex"); println(myList); // Remove an element myList -= "Welcome"; // print second element println(myList(1)); } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala \>scala Demo
ListBuffer(Zara, Nuha, Ayan) ListBuffer(Zara, Nuha, Ayan, Welcome, To, Howcodex) Nuha