Scala Vector is a general purpose immutable data structure where elements can be accessed randomly. It is generally used for large collections of data.
The following is the syntax for declaring an Vector variable.
var z : Vector[String] = Vector("Zara","Nuha","Ayan")
Here, z is declared as an vector of Strings which has three members. Values can be added by using commands like the following −
var vector1: Vector[String] = z + "Naira";
Below is an example program of showing how to create, initialize and process Vector −
import scala.collection.immutable.Vector object Demo { def main(args: Array[String]) = { var vector: Vector[String] = Vector("Zara","Nuha","Ayan"); // Add an element var vector1: Vector[String] = vector :+ "Naira"; // Reverse an element var vector2: Vector[String] = vector.reverse; // sort a vector var vector3: Vector[String] = vector1.sorted; println(vector); println(vector1); println(vector2); println(vector3); } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala \>scala Demo
Vector(Zara, Nuha, Ayan) Vector(Zara, Nuha, Ayan, Naira) Vector(Ayan, Nuha, Zara) Vector(Ayan, Naira, Nuha, Zara)