Scala list init() operation with examples

 131 total views,  2 views today

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

Scala init() operation allows us to take/retrieve part of the collection by eliminating the last element. init() operation will return new collection by taking all the elements but without the last element.init() will omit the last element of the collection.

Scala init() operation is applicable to all types of Scala collections.

init() Syntax

def init: List[A]

The initial part of the collection without its last element

Scala List init() examples

In this init() example, we have created a list and applied init() method to take/collect part of the collection and eliminate the last element.

object InitTest {

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

    //Create a list
    var list = List(6, 2, 3, 4, 5, 6, 7, 8);

    //Apply init() and print collection
    list.init.foreach(println)

  }
}

Output

6
2
3
4
5
6
7

Let us see another example of the Scala init() method.Here we have created a list of strings. When you apply init(), the last element ‘e’ has been omitted. Check out the output.

object InitTest {

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

    //Create a list
    var list = List("a", "b", "c", "d", "e");

    //Apply init() and print collection
    list.init.foreach(println)

  }
}

Output

a
b
c
d

ReferencesScala init() operation

Would you like to learn more about Scala features, please check out Scala – a complete guide series. In this tutorial guide, you will find useful Scala functions that can be applied to the collection.

I hope you like this tutorial and you were able to understand the Scala list init() operation with examples.

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!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.