Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala How to get sublist by index

Tags:

scala

I have a List(1 ,2 ,3 ,4 ,5) and trying to get a sublist: List(3, 4) from it by the following way:

List(1 ,2 ,3 ,4 ,5).slice(this.size - 3 , this.size - 1 )

But I got an error

error: value size is not a member of object

How can I use "this" parameter in Scala just like in Java. Are there other ways to achieve the goal. Thank you so much.

like image 681
Viet Son Avatar asked May 14 '15 10:05

Viet Son


2 Answers

You should first declare the list, and then refer to the list using its name list, not this:

val list = List(1 ,2 ,3 ,4 ,5)
list.slice(list.size -3, list.size -1)

If you really want to do this in one line, then use reverse, but it's not very efficient:

List(1 ,2 ,3 ,4 ,5).reverse.slice(1, 3).reverse

By the way, that code wouldn't be valid in Java either. this refers to the enclosing object, not to the list.

like image 186
dcastro Avatar answered Nov 20 '22 15:11

dcastro


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) 

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

like image 5
Biswanath Avatar answered Nov 20 '22 16:11

Biswanath