Scala List dropRight() operation with examples

 234 total views,  1 views today

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

dropRight() operation is a useful operation of the Scala List which allows us to drop last N elements from the list or collection. When you call this operation on a Scala list, it returns a new collection by dropping the last N elements. i.e., drop N elements from the right.

dropRight() Syntax

def dropRight(n: Int): List[A]

The rest of the collection without its n last elements.

Scala List dropRight() example 1

In this example, we have N=2 and the size of the list is 4. It will remove the last 2 elements from the right.

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

    //Initialize N
    var n: Int = 2

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

    //Drop last  N elements from the right  and print
    list.dropRight(n).foreach(println _)
  }
}

Output

a
b

Scala List dropRight() example 2

In this example, the size of the list is 4 but N = 5 which is greater than the size. So dropRight() will return the empty sequence or collection.

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

    //Initialize N
    var n: Int = 5

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

    //Drop last  N elements from the right  and print
    list.dropRight(n).foreach(println _)
  }
}

<Empty Output>

ReferencesScala dropRight() 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 Scala list dropRight() 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!.