Explain the difference between a Seq and a List in Scala.
Instruction: Provide definitions for both Seq and List and discuss the differences and scenarios of their usage.
Updated
Seq is a sequence abstraction: elements have an order and may repeat. List is a particular immutable, singly linked sequence. A general sequence interface does not promise the access costs of a particular implementation.
In Scala 2.13 and Scala 3, the unqualified Seq alias is the immutable sequence type. Use the broader collection sequence type explicitly if accepting mutable implementations is intentional:
import scala.collection.mutable.ArrayBuffer
def broadSize(values: scala.collection.Seq[Int]): Int = values.size
@main def sequenceExample(): Unit = {
val values: Seq[Int] = List(1, 2, 2)
val buffer = ArrayBuffer(1, 2)
assert(values == List(1, 2, 2))
assert(broadSize(buffer) == 2)
assert((0 :: values.toList) == List(0, 1, 2, 2))
}
A List supports constant-time head, tail and prepend operations on nonempty lists; indexing, finding its length and appending require traversal. Nil.head and Nil.tail throw, so use matching or safe alternatives when emptiness is possible. An immutable list can still contain mutable elements. Immutable list behavior
Use a sequence interface when callers should not depend on a concrete representation. Use List for head-oriented traversal and prepend-heavy construction; consider Vector or an appropriate indexed sequence when random access dominates. If a method accepts a mutable sequence through a broad interface, that reference is not a snapshot. Scala 2.13 collection migration
Related Questions
-
easy
-
medium
-
medium
-
medium
-
hard
-
hard