Open In App

Difference between a Seq and a List in Scala

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Sequences of items are represented in Scala using two different collection types: Seq and List. Nonetheless, there are significant distinctions between them in terms of use, implementation, and mutability.

Mutability:

  • Seq: Sequences of items, known as seqs, may be either changeable or immutable. It is not certain that the components will be in a certain sequence.
  • List: A list is an ordered collection of items represented by a concrete implementation of the Seq trait. Its components cannot be changed once they are produced, making it immutable.

Implementation:

  • Seq: As a trait, Seq offers a general interface for sequences, supporting various implementations such as Array, Vector, List, and so on.
  • List: A singly linked list is used to implement the list, in which each entry is saved along with a reference to the one after it.

Usage:

  • Seq: When working with a general sequence of items and without requiring specialized List attributes or other concrete implementations, use Seq.
  • List: Use the list when you have a special requirement for an ordered collection that is immutable and provides quick access to the top of the list.

Code and Screenshot

Here’s an illustration of how Seq and List vary from one another:

Scala
object Main {
  def main(args: Array[String]): Unit = {
    // Creating a Seq
    val seq: Seq[Int] = Seq(1, 2, 3, 4, 5)

    // Creating a List
    val list: List[Int] = List(1, 2, 3, 4, 5)

    println("Seq elements: " + seq)
    println("List elements: " + list)
  }
}

Output Screenshot:

Screenshot-(365)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads