Scala如何通过索引获取子列表

Vie*_*Son 10 scala

我有一个List(1,2,3,4,5)并尝试通过以下方式获取子列表:List(3,4):

List(1 ,2 ,3 ,4 ,5).slice(this.size - 3 , this.size - 1 )
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误

error: value size is not a member of object
Run Code Online (Sandbox Code Playgroud)

如何像在Java中一样在Scala中使用"this"参数.是否有其他方法可以实现目标.非常感谢.

dca*_*tro 13

您应首先声明列表,然后使用其名称引用列表,而list不是this:

val list = List(1 ,2 ,3 ,4 ,5)
list.slice(list.size -3, list.size -1)
Run Code Online (Sandbox Code Playgroud)

如果你真的想在一行中做这个,那么使用reverse,但效率不高:

List(1 ,2 ,3 ,4 ,5).reverse.slice(1, 3).reverse
Run Code Online (Sandbox Code Playgroud)

顺便说一句,该代码在Java中也无效.this是指封闭对象,而不是列表.


Bis*_*ath 5

If you want last 3 or n elements, you can use takeRight(3) or takeRight(n).

Edit based on the question edit:

If you need to not take first f and last l elements then

List(1,2,3,....n).drop(f).dropRight(l) 
Run Code Online (Sandbox Code Playgroud)

For your case it will be List(1,2,3,4,5).drop(2).dropRight(1)