List in Scala is a collection that stores data in the form of a linked-list. The list is an immutable collection which means the elements of a list cannot be altered after the list is created. We can access elements of the array using the index of the element.
Accessing the first element of the list
The first element of the list can be easily accessed using one of the two ways listed below:
- By using the index value (0) of the first element
- By using the list.head method
Accessing the first element using the index value,
We can easily access the first element of the list by using its index value. And the indexing of the list is similar to that of an array i.e. the indexing starts at 0.
So, the first element will be at 0 index in the list.
Syntax:
Program to illustrate the working of our solution
Output:
Accessing the first element of the list using the list.head method
There are many inbuilt methods to support the functioning of a data structure in Scala. List is not an exception to that; the first element can be accessed using the inbuilt function head.
Syntax:
Program to illustrate the working of our solution
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer