Let's say, I have a list. If I want to return something at the index of that list, I can just pass the lists' val, the index. Like so.
val list = List(1, 2, 3)
list(0) //Int = 1
But what if I want items at multiple indexes on this list? I want to be able to do this... list(0, 1) and get a collection of the items at those indices.
This is crazily simple in Ruby. Anyone have any suggestions?
You can flip the logic around, so that for each index, you're getting the index, you retrieve the element at that index. Since you are using the
applymethod onList, there are several shorthand expressions of this logic:It's worth noting that since these are all
mapsonindices, the resulting collection will generally have the same type asindices, and notlist:This can be an undesirable property here. One solution to this is to use
breakOut(inscala.collection):You can read more about breakOut here. The following solutions also maintain the collection type of
listwhen possible by performing operations onlistinstead ofindeces:If you are looking for a contiguous range of the list, you might consider using
slice:You could also use
dropandtake(and thedropRight,takeRightversions) to a similar effect:For more complex versions of this type of filtering, you might be interested in the
zipWithIndexmethod, which would allow you to express arbitrary logic on the index: