Scala Tutorial - Learn How To Use TakeRight Function With Examples
Overview
In this tutorial, we will learn how to use the takeRight function with examples on collection data structures in Scala. The takeRight function is applicable to both Scala's Mutable and Immutable collection data structures.
The takeRight method takes an integer N as parameter and will use it to return a new collection consisting of the last N elements.
As per the Scala documentation, the definition of the takeRight method is as follows:
def takeRight(n: Int): Repr
The takeRight method is a member of IterableLike trait.
Steps
1. How to initialize a Sequence of donuts
The code below shows how to create a Sequence of donuts 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 take the last N elements using the takeRight function
Using the donuts sequence from Step 1, you can use the takeRight method to return a new collection with donut elements consisting of the last N parameter of the take method.
println("\nStep 2: How to take the last N elements using the takeRight function")
println(s"Take the last donut element in the sequence = ${donuts.takeRight(1)}")
println(s"Take the last two donut elements in the sequence = ${donuts.takeRight(2)}")
println(s"Take the last three donut elements in the sequence = ${donuts.takeRight(3)}")
You should see the following output when you run your Scala application in IntelliJ:
Step 2: How to take the last N elements using the takeRight function
Take the last donut element in the sequence = List(Glazed Donut)
Take the last two donut elements in the sequence = List(Strawberry Donut, Glazed Donut)
Take the last three donut elements in the sequence = List(Plain Donut, Strawberry Donut, Glazed Donut)
NOTE:
- If you pass in an integer parameter N to the takeRight method where N is larger than the size of the collection, the takeRight method will return all the elements in the collection.
Summary
In this tutorial, we went over the following:
- How to initialize a Sequence of donuts
- How to take the last N elements using the takeRight 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 the takeWhile function.