Home > Enterprise >  Indexing/Slicing of Collections in Scala
Indexing/Slicing of Collections in Scala

Time:12-04

I saw some really cool methods to operate on Scala Collections but I wanted to know how can one do the slicing operation in Scala? I see methods like dropLeft take but curious to know if something simpler like indexing or slice exists in Scala.

For example:

val aString = "I want this word" val aList = List(1,2,3,4)

should return:

val slicedString = aString.slice(7,11) => "this" //JavaScript type

and

val slicedList = aList.slice(0,2) => List(1,2) //JavaScript type

or indexing like how it's done in python:

val slicedString = aString(7:11) => "this"

val slicedList = aList(0:2) => List(1,2)

CodePudding user response:

Had you bothered to consult the ScalaDocs you would have found what you're looking for.

aString.slice(7,11)  //res0: String = this
aList.slice(0,2)     //res1: List[Int] = List(1, 2)
  • Related