Open In App
Related Articles

How to get the first element of List in Scala

Improve Article
Improve
Save Article
Save
Like Article
Like

In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. Let’s see how to get the first element of given List in Scala.
List in Scala contains many suitable methods to perform simple operations like head(), tail(), isEmpty(). Coming to list, head() method is used to get the head/top element of the list. 
below are examples to get first element of list. 

Example : 
 

scala




// Scala program to print immutable lists
import scala.collection.immutable._
 
// Creating object
object GFG
{
    // Main method
    def main(args:Array[String])
    {
        // Creating and initializing immutable lists
        val mylist: List[String] = List("Geeks", "For", "geeks", "is",
                                        "a", "fabulous", "portal")
 
        println("The head of the list is:")
        println(mylist.head)
    }
}


Output: 
 

The head of the list is:
Geeks

Example :
 

scala




// Scala program to creating a uniform list
import scala.collection.immutable._
 
// Creating object
object GFG
{
    // Main method
    def main(args:Array[String])
    {
        // Repeats Scala three times.
        val myList = List.range(10, 19)
        println(myList)
 
        println("First element is: " + myList.head)
    }
}


Output: 
 

List(10, 11, 12, 13, 14, 15, 16, 17, 18)
First element is: 10

 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 19 Nov, 2021
Like Article
Save Article
Previous
Next
Similar Reads