Today we will look into Scala slice function.
Scala slice function is available in the following API classes:
We will pick-up each API and discuss them in-depth with suitable examples in next section.
In Scala API, ‘slice’ function is used to select an interval of elements. It takes two parameters of “Int” type and returns subset or whole or none element(s) of original Collection (or String or Array). Real-world slice scenario:- We can use this slice function in our regular real-world life too as shown below. Here Bread.slice(0,10) means take bread slices from 0 to 9 so total 10 Bread slices.(Just to resemble Scala’s slice function here I’m using zero, but assume this as one.) slice function syntax: In Scala Standard Library (API), this slice function is defined as follows:
def slice(from-index: Int, until-index: Int): ScalaAPIClass[A]
Here “ScalaAPIClass” means any Scala Collection class (which supports index based access like Seq, List etc), String, Array classes. Example:- The following function is defined in Scala API’s Seq class.
def slice(from-index: Int, until-index: Int): Seq[A]
slice function Parameters: The “slice” function parameter’s usage are described in the following table:
S.No. | Function Params | Usage |
---|---|---|
1. | First Parameter | Starting index (Inclusive). It should be zero or any any positive integer less than the length of the Collection or String or Array. |
2. | Second Parameter | Ending index (Exclusive). |
slice function extract elements starting from ‘first-index’ (Inclusive) to ‘until-index’ (exclusive). Here elements numbers for an Array of Numbers, Characters for a String, an object for a Collection.
In Scala API, Array class defines slice function as follows:
def slice(from: Int, until: Int): Array[T]
Here ‘from’ is the starting index (Inclusive) of the Array and ‘until’ is the ending index (Exclusive) of the Array. Array slice Function Examples:
scala> val marksArray = Array(56,79,60,99,71)
marksArray: Array[Int] = Array(56, 79, 60, 99, 71)
Int of Array with 5 values are created so it’s index start value is 0 and index end value is 4. It’s length = 5 Let us play with slice function now.
scala> marksArray.slice(0,2)
res0: Array[Int] = Array(56, 79)
It starts with 0 index that is first element and retrieves all elements until 2 means index = 1 that’s why we got 0th element and 1st element here.
scala> marksArray.slice(3,4)
res1: Array[Int] = Array(99)
We can access with any indices range.
scala> marksArray.slice(3,3)
res2: Array[Int] = Array()
If we give same values for start and end like above we will get empty array why? Start index = 3 End index = 3 - 1 = 2 It’s not possible to retrieve a set of elements from an array from 3 to 2 indices right.
scala> marksArray.slice(-1,3)
res3: Array[Int] = Array(56, 79, 60)
If we give -ve values, it just starts with available index as shown above.
scala> marksArray.slice(0,5)
res4: Array[Int] = Array(56, 79, 60, 99, 71)
If we give 2nd parameter value in beyond it’s available index as shown above (Available max index value in marksArray is 4 only as it’s length = 5), it just ignores that value and returns up-to available index only. NOTE:- Unlike Java, it does not throw any ArrayIndexOutOfBoundsException.
In Scala’s Standard API, most of the classes defines this slice function which supports index based elements access. For instance, List class defines this function as shown below:
def slice(from: Int, until: Int): List[A]
List slice function examples:- Same as Array examples, we will get same results for any Collection API.
scala> val list = List(56, 79, 60, 99, 71)
list: List[Int] = List(56, 79, 60, 99, 71)
scala> list.slice(0,2)
res5: List[Int] = List(56, 79)
scala> list.slice(3,4)
res6: List[Int] = List(99)
scala> list.slice(3,3)
res7: List[Int] = List()
scala> list.slice(-1,3)
res8: List[Int] = List(56, 79, 60)
scala> list.slice(0,5)
res9: List[Int] = List(56, 79, 60, 99, 71)
If we access an empty list, we will get empty list only as shown below
scala> val list2 = List()
list2: List[Nothing] = List()
scala> list2.slice(0,1)
res10: List[Nothing] = List()
In Scala API, “StringOps” class is defined in scala.collection.immutable package. It defines slice function as shown below:
def slice(from: Int, until: Int): String
NOTE:- In Scala, we use Java’s String class. But this class does NOT have slice function. When we use slice function on Java’s String objects, Scala Compiler internally converts this String object into StringOps class object to use this slice function. (Not only slice function many more. See Scala API for more information.) That means “StringOps” is an implicit class of String class. String slice’s function examples:-
scala> val str = "Hello I'm doing good. How are you?"
str: String = Hello I'm doing good. How are you?
scala> str.slice(6,9)
res8: String = I'm
As we know, String index starts with zero. Here from-index = 6 means until-index = 9 (It’s exclusive so we need to consider till index = 8 only) String’s substring function works same as it’s slice function as shown below:
scala> str.substring(6,9)
res12: String = I'm
Here both str.slice(6,9) and str.substring(6,9) are returning same value. slice Vs substring Difference between slice and substring functions of String class
NOTE:- In Scala, We can access String characters just like an Array elements as shown below:
scala> str(0)
res0: Char = H
Here it returns a Char, but not a String
scala> str(-1)
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(String.java:658)
at scala.collection.immutable.StringOps$.apply$extension(StringOps.scala:38)
... 33 elided
scala> str.length
res2: Int = 34
scala> str(34)
java.lang.StringIndexOutOfBoundsException: String index out of range: 34
at java.lang.String.charAt(String.java:658)
at scala.collection.immutable.StringOps$.apply$extension(StringOps.scala:38)
... 33 elided
NOTE:- If we try to access String characters in out of range, we get StringIndexOutOfBoundsException as shown above. String’s character access returns Char where as substring & slice functions returns String as shown below.
scala> str(0)
res4: Char = H
scala> str.substring(0,1)
res5: String = H
scala> str.slice(0,1)
res6: String = H
That’s it all about “Scala’s slice function” usage. We will discuss some more Scala concepts in my coming posts. Reference: Scala API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.