1
val res1 = -1
val res2: List[Int] = List.empty
val res3 = -1

After some operations, res2 can have multiple elements, but all values must be -1

How I can made a pattern matching using this list ?

before this, when res2 was an Int, I used this pattern:

(r1, r2, r3) match {
  case (-1, -1, -1) => Success()
  case _ => throw new Exception("Invalid results")
}

now I need something like

(r1, r2, r3) match {
  case (-1, List(-1, -1, ...), -1) => Success()
  case _ => throw new Exception("Invalid results")
}

I know I can use List.forall or List.exists, but this is outside matching pattern.

Update: I found a solution which works fine

val r2res = r2.forall(x => x == -1)

 (r1, r2res, r3) match {
   case (-1, true, -1) => Success()
   case _ => throw new Exception("Invalid results")
 }

Feel free to post a reply if exist a method to match directly the result of res2. Thanks

2 Answers 2

4

You can use pattern guards in pattern matching:

(r1, r2, r3) match {
  case (-1, l:List[Int], -1) if l.forall(_ == -1) => Success()
  case _ => throw new Exception("Invalid results")
}
Sign up to request clarification or add additional context in comments.

2 Comments

that's what I searched for. Thanks
@AlleXyS was glad to help!
1

Try combining pattern binder with a guard

(res1, res2, res3) match {
  case (-1, (l @ h :: _), -1) if l.forall(_ == -1) => // ok
  case _ => // nok
}

Note I used (l @ h :: _) pattern assuming empty list should not qualify because

assert(List.empty[Int].forall(_ == -1))   // ok

1 Comment

thanks for your reply. I checked Guru Stron as solution because I need that all items to be -1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.