Home »
Scala
Difference between Sequence and List in Scala
By IncludeHelp Last updated : October 20, 2024
Scala programming language supports the usage of many collections for better working of its programs. In this article, we will be discussing about two of them:
- Sequence in Scala
- List in Scala
Scala Sequence
Sequence in Scala is a collection that stores elements in a fixed order. It is an indexed collection with 0 index.
Declaration Syntax
Sequence : var coll_Name = Seq(elementList)
Scala List
List is Scala is a collection that stores elements in the form of a linked list.
Declaration Syntax
list : var coll_Name = List(elementList)
Difference between Sequence and List
Both sequence and list are collections that can store data but the sequence has some additional features over the list. In Scala, a list is a specialized collection that is optimized and commonly used in functional programming. There are some limitations of it but is commonly used to store data because of being optimized and faster compilation, also specialized functions available add a bit more functionality.
Examples of sequence and list to understand the difference
Let's see a basic program for each collection to understand the difference –
Example of list
// Program to illustrate the working of list in Scala,
object MyClass {
def main(args: Array[String]) {
// creating List of String values
val progLang : List[String] = List("scala", "javaScript", "Java", "C#")
// printing the list
println("The list of programming languages is "+ progLang)
}
}
Output:
The list of programming languages is List(scala, javaScript, Java, C#)
Example of sequence
// Program to illustrate the working of sequence in scala,
object MyClass {
def main(args: Array[String]) {
// creating Sequence of String values
val progLang : Seq[String] = Seq("scala", "javaScript", "Java", "C#")
// printing the list
println("The list of programming languages is "+ progLang)
}
}
Output:
The list of programming languages is List(scala, javaScript, Java, C#)
Difference Summary
Here, we can see that in Scala, if we create a sequence it is by default initialized as a list. But if we want to create a sequence other than list, we need to create it explicitly using specific creation syntax. More on collection hierarchy.