4

I'm new to Scala. I see that there's a slice method for Arrays that can return a consecutive slice, like so:

scala> "zero|one|two|three|four|five".split("\\|").slice(2,5)
res3: Array[String] = Array(two, three, four)

Is there syntactic sugar somewhere for taking an arbitrary, non-consecutive, non-ascending sub-array? Something like:

scala> "zero|one|two|three|four|five".split("\\|").fictionalMethod(4,1,5)
res3: Array[String] = Array(four, one, five)

1 Answer 1

7

The shortest line using only standard library functions I can think of would be

Array(4, 1, 5) map "zero|one|two|three|four|five".split("\\|")
Sign up to request clarification or add additional context in comments.

5 Comments

Would that end up splitting the string multiple times, once per array index?
By splitting the string, I should have said "re-evaluating "zero|one|two|three|four|five".split("\\|")" multiple times.
In this case no, it won't -- but you're right that it's precariously close to doing so. Array(4, 1, 5) map "(zero|one|two|three|four|five".split("\\|").apply(_)) would evaluate multiple times.
Can't you skip the apply as well? Works fine for me without it.
+1 clever reverse thinking - i.e. give the indices before the operation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.