Scala List head() operation with examples

 147 total views,  2 views today

Welcome to Scala series.In this tutorial, you will learn about Scala List head() operation with examples.

Scala List

  • List() is a collection to store values in an ordered fashion. It allows store duplicate values.
  • List() extends LinearSeq() trait and it is based on Last In First Out model.
  • List() is part of both immutable and mutable collection package of Scala. Immutable List allows us to apply a function on List but resulting in the creation of a new list every time. It doesn’t allow us the source. On the other hand, the mutable list allows modifying the source itself.
  • List() is a collection to store values in an ordered fashion.

head() In order to get first/head element of the list,usually in Java we get the data of zero index.But in Scala, we have an operation head() to get the head/first element of the list. Similarly you can use tail() to get the elements other than head element.

head() syntax

def head: A

It always returns the first element of the list.

Scala List head() operation examples

object Test {
  def main(args: Array[String]): Unit = {

    var list: List[String] = List("a", "b", "c", "d")

    println(list.head)
  }
}

Output

a
object Test {
  def main(args: Array[String]): Unit = {

    var list: List[Int] = List(1, 2, 3, 4, 5, 6)

    println(list.head)
  }
}

Output

1

References: Scala List head operation

I hope you like this tutorial and you were able to understand about Scala list head operation.

Thanks for reading and please give us a thumb up and comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.