Seq and List differences in Scala

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-10-12 14:09:52 Viewed : 262


In Scala, both Seq and List are collection types, but they have some differences in their characteristics and usage.

Seq is a trait (interface) that represents a sequence of elements. Its a more general concept and can be implemented by various collection types, including List, Vector, Array, and more. List, on the other hand, is a specific implementation of Seq.

Here are the key differences between Seq and List in Scala:

  1. Immutability:

    • List is an immutable data structure. Once you create a List, you cannot modify it. Any operation that seems to modify a List will create a new List with the modified elements.
    • Seq can be either mutable or immutable, depending on the concrete implementation. For example, scala.collection.immutable.Seq is immutable, while scala.collection.mutable.Seq is mutable.
  2. Performance:

    • List is optimized for fast head (first element) and tail (rest of the elements) operations, making it a good choice for functional programming and pattern matching use cases.
    • Other Seq implementations like Vector are optimized for fast random access, which means they are more suitable for scenarios where you frequently access elements by their indices.

Here are some examples of using List and Seq in Scala:

scala
// Creating a List val myList = List(1, 2, 3, 4, 5) // Creating a Seq (specifically, an immutable one) val mySeq = Seq(1, 2, 3, 4, 5) // Accessing elements in a List val firstElement = myList.head // 1 val restOfList = myList.tail // List(2, 3, 4, 5) // Accessing elements in a Seq val elementAtIndex2 = mySeq(2) // 3 // Adding elements to a List (creates a new List) val newList = myList :+ 6 // List(1, 2, 3, 4, 5, 6) // Adding elements to a Seq (creates a new Seq) val newSeq = mySeq :+ 6 // Seq(1, 2, 3, 4, 5, 6) // Note that the original collections are not modified by these operations

In most cases, using List is a good choice because of its immutability and performance characteristics. However, if you need to optimize for specific use cases, you can consider other Seq implementations such as Vector or choose between mutable and immutable Seq based on your requirements.

Search
Related Articles

Leave a Comment: