Difference between Sequence and List in Scala

Scala | Sequence vs. List: Here, we will see the difference between two data structures in Scala. We will learn about the difference using examples and working codes.
Submitted by Shivang Yadav, on January 03, 2021

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:

  1. Sequence in Scala
  2. List in Scala

Definitions:

Sequence in Scala is a collection that stores elements in a fixed order. It is an indexed collection with 0 index.

List is Scala is a collection that stores elements in the form of a linked list.

Declaration Syntax:

Both have similar declaration syntax which is as follows:

Sequence : var coll_Name = Seq(elementList)

list : var coll_Name = List(elementList)

Both 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.

Let's see a basic program for each collection to understand the difference,

// 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#)
// 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#)

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.