I'm looking for an elegant way to get a slice of a list from element n onwards without having to specify the length of the list. Lets say we have a multiline string which I split into lines and then want to get a list of all lines from line 3 onwards:
string.split("\n").slice(3,X) // But I don't know what X is...
What I'm really interested in here is whether there's a way to get hold of a reference of the list returned by the split
call so that its length can be substituted into X
at the time of the slice
call, kind of like a fancy _
(in which case it would read as slice(3,_.length)
) ? In python one doesn't need to specify the last element of the slice.
Of course I could solve this by using a temp variable after the split, or creating a helper function with a nice syntax, but I'm just curious.
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.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
Just drop first n elements you don't need:
List(1,2,3,4).drop(2) res0: List[Int] = List(3, 4)
or in your case:
string.split("\n").drop(2)
There is also paired method .take(n)
that do the opposite thing, you can think of it as .slice(0,n)
.
In case you need both parts, use .splitAt
:
val (left, right) = List(1,2,3,4).splitAt(2) left: List[Int] = List(1, 2) right: List[Int] = List(3, 4)
The right answer is takeRight(n)
:
"communism is sharing => resource saver".takeRight(3) //> res0: String = ver
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With