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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With