Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
The following is the syntax for declaring an Seq variable.
val seq: Seq[Int] = Seq(1, 2, 3, 4, 5)
Here, seq is declared as an Seq of numbers. Seq provides commands like the following −
val isPresent = seq.contains(4); val contains = seq.endsWith(Seq(4,5)); var lastIndexOf = seq.lasIndexOf(5);
Below is an example program of showing how to create, initialize and process Seq −
import scala.collection.immutable.Seq object Demo { def main(args: Array[String]) = { var seq = Seq(1, 2, 3, 4, 5, 3) // Print seq elements seq.foreach{(element:Int) => print(element + " ")} println() println("Seq ends with (5,3): " + seq.endsWith(Seq(5, 3))) println("Seq contains 4: " + seq.contains(4)) println("Last index of 3: " + seq.lastIndexOf(3)) println("Reversed Seq" + seq.reverse) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala \>scala Demo
1 2 3 4 5 3 Seq ends with (5,3): true Seq contains 4: true Last index of 3: 5 Reversed SeqList(3, 5, 4, 3, 2, 1)