Mark Silberbauer Mark Silberbauer - 8 months ago 49
Scala Question

In Scala, how to get a slice of a list from nth element to the end of the list without knowing the length?

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
call so that its length can be substituted into
at the time of the
call, kind of like a fancy
(in which case it would read as
) ? 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.


Just drop first n elements you don't need:

res0: List[Int] = List(3, 4)

or in your case:


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)