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

前端 未结 4 836
佛祖请我去吃肉
佛祖请我去吃肉 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:21

    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)
    

提交回复
热议问题