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

前端 未结 4 748
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-02 05:34

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 spl

4条回答
  •  清酒与你
    2021-02-02 06:08

    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)
    

提交回复
热议问题