”;
Scala Vector is a general purpose immutable data structure where elements can be accessed randomly. It is generally used for large collections of data.
Declaring Vector Variables
The following is the syntax for declaring an Vector variable.
Syntax
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 −
Command
var vector1: Vector[String] = z + "Naira";
Processing Vector
Below is an example program of showing how to create, initialize and process Vector −
Example
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.
Command
>scalac Demo.scala >scala Demo
Output
Vector(Zara, Nuha, Ayan) Vector(Zara, Nuha, Ayan, Naira) Vector(Ayan, Nuha, Zara) Vector(Ayan, Naira, Nuha, Zara)
Advertisements
”;