Scala Tutorial - Learn How To Use Drop Function
Overview
In this tutorial, we will learn how to use the drop function on collection data structures in Scala. The drop function is applicable to both Scala's Mutable and Immutable collection data structures.
The drop method takes an integer parameter N and will return a new collection that does not contain the first N elements.
As per the Scala documentation, the definition of the drop method is as follows:
def drop(n: Int): Repr
The drop method is a member of the IterableLike trait.
Steps
1. How to initialize a Sequence of donuts
The code below shows how to initialize a Sequence of Donut elements of type String.
println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")
You should see the following output when you run your Scala application in IntelliJ:
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
2. How to drop the first element using drop function
The code below shows how to remove the first element from the Donut Sequence by using the drop method.
println("\nStep 2: How to drop the first element using drop function")
println(s"Drop the first element in the sequence = ${donuts.drop(1)}")
You should see the following output when you run your Scala application in IntelliJ:
Step 2: How to drop the first element using drop function
Drop the first element in the sequence = List(Strawberry Donut, Glazed Donut)
3. How to drop the first two elements using the drop function
The code below shows how to remove the first two elements from the Donut Sequence by using the drop method.
println("\nStep 3: How to drop the first two elements using the drop function")
println(s"Drop the first and second elements in the sequence = ${donuts.drop(2)}")
You should see the following output when you run your Scala application in IntelliJ:
Step 3: How to drop the first two elements using the drop function
Drop the first and second elements in the sequence = List(Glazed Donut)
NOTE:
- As per the examples in Step 1 and Step 2, it should be fairly obvious that the drop method allows you to drop the first N elements from a given collection, where N is specified by the parameter of the drop method.
Summary
In this tutorial, we went over the following:
- How to initialize a Sequence of donuts
- How to drop the first element using drop function
- How to drop the first two elements using the drop function
Tip
Source Code
The source code is available on the allaboutscala GitHub repository.
What's Next
In the next tutorial, I will show you how to use dropWhile function.