3

I have a source file like this:

replace 1 3 xyz
reverse 0 2
print 1 4

And I would like to assign these elements line by line using Array:

val Array(action, start, end, sub) = src.next.split(“ “)

As you can see the 4th element is optional, and I don’t know how I can manage this inconsistency. Is there any way to make the last assignment optional?

0

2 Answers 2

3
val Array(action, start, end, x @ _*) = src.next.split(" ")

This will match action, start, end to the first 3 elements, and x to a Seq[String]. You can then use x.headOption to get the 4th element as an Option. If there are more than 4, they will all be contained in x

val line = "replace 1 3 xyz"
val Array(action, start, end, x @ _*) = line.split(" ")
// action: String = replace
// start: String = 1
// end: String = 3
// x: Seq[String] = Vector(xyz)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Perfect.
2

There are a number of different ways to approach this. Here's one that is concise but it turns everything into an Option.

val line = "reverse 0 2".split(" ")

val Seq(action, start, end, sub) = 0.to(3).map(line.lift)
//action: Option[String] = Some(reverse)
//start: Option[String] = Some(0)
//end: Option[String] = Some(2)
//sub: Option[String] = None

If you only want the 4th as an Option then you have to make it a separate assignment.

val Array(action, start, end) = line.take(3)
val sub                       = line.lift(3)

Comments

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.