Introduction
In Scala, a List is an immutable sequence of elements. Unlike Arrays, which are mutable, Lists provide a functional approach to handling collections.
Creating a List
A List can be created easily using the List
keyword:
|
|
List Concatenation (:::
)
To concatenate two lists, use the :::
operator:
|
|
Prepending Elements (::
)
The ::
operator is used to prepend a new element to the beginning of an existing list:
|
|
Lists vs Arrays
Feature | List | Array |
---|---|---|
Mutability | Immutable | Mutable |
Usage | Functional, persistent data structures | Performance-efficient for indexed access |
Modification | Elements cannot be modified | Elements can be updated |
Key Takeaway
Use Lists when working with immutable collections in a functional style, and Arrays when you need mutable collections with fast indexed access.