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

Scala

Scala Problem Overview


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.

Scala Solutions


Solution 1 - Scala

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)

Solution 2 - Scala

The right answer is takeRight(n):

"communism is sharing => resource saver".takeRight(3)
                                              //> res0: String = ver

Solution 3 - Scala

You can use scala's list method 'takeRight',This will not throw exception when List's length is not enough, Like this:

val t = List(1,2,3,4,5);
t.takeRight(3);
res1: List[Int] = List(3,4,5)

If list is not longer than you want take, this will not throw Exception:

val t = List(4,5);
t.takeRight(3);
res1: List[Int] = List(4,5)

Solution 4 - Scala

get last 2 elements:

List(1,2,3,4,5).reverseIterator.take(2)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark SilberbauerView Question on Stackoverflow
Solution 1 - Scalaom-nom-nomView Answer on Stackoverflow
Solution 2 - ScalaValView Answer on Stackoverflow
Solution 3 - ScalahaiyangView Answer on Stackoverflow
Solution 4 - ScalacloudView Answer on Stackoverflow