What is the list.head method in Scala?
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.
Syntax
list_name.head
// where the list_name is the name of the list.
Parameters
This function does not require a parameter.
Return value
The list.head function returns the reference to the list’s first element.
-
list.headdoes not remove that element from the list. -
If the list is
empty, then the function throws anerror.
Code
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);}