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 last element:
The last element of the array can be accessed by 2 methods.
- By using the length of the list.
- By using the last function.
Accessing the last element using the length of the list
We will use the index of the list to find the element. For this, we will find the length of the list and use (length-1) as index to access the last element.
Syntax:
Example to find the last element using the length of the list
Output:
Accessing the last element using the length of the list
To find the last element of the array, we will use the last function.
Syntax:
Example to find the last element using the last function
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer