The list.head
function in Scala returns the reference of the first element in the list.
The image below shows the visual representation of the list.head
function.
list_name.head
// where the list_name is the name of the list.
This function does not require a parameter.
The list.head
function returns the reference to the list’s first element.
list.head
does not remove that element from the list.
If the list is empty
, then the function throws an error
.
The below code shows how to use the list.head
function in Scala.
object Main extends App {var list = List(1,4,3,2,0)// list = 1 -> 4 -> 3 -> 2 -> 0println("Following are the elements in List before using list.head: " + list);println("The element on the head of list: "+list.head);println("Following are the elements in list after using list.head: " + list);}