2

I try to match after some case applied. Kind of nested cases/matches:

val x1 = 2 // or 1, 3 ...
val str = x1 match {   // scala.MatchError: 1 (of class java.lang.Integer)

  case x if(x > 1) => "x"+x match {case "x1" => "yes"}

  // updated:
  case _ => "nope"
}
println (str)

It fails with scala.MatchError exception.

Is it possible? It seems I've seen something similar.

Exception in thread "main" scala.MatchError: x2 (of class java.lang.String) at pattern_matching.PatternMatchingTest$delayedInit$body.apply(PatternMatchingTest.scala:32) at scala.Function0$class.apply$mcV$sp(Function0.scala:40) at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) at scala.App$$anonfun$main$1.apply(App.scala:71) at scala.App$$anonfun$main$1.apply

1 Answer 1

4

The problem you are hitting is that your example input (val x1 = 1) doesn't match the one case you gave (since x1 is not greater than 1). You will need to either modify your existing case (eg. change the if to something like if(x >= 1)) or add at least one more case, and should probably consider a default case. eg.:

val str = x1 match {   // scala.MatchError: 1 (of class java.lang.Integer)
  case x if(x > 1) => "x"+x match {case "x1" => "yes"}
  case _ => "no match"
}
Sign up to request clarification or add additional context in comments.

3 Comments

even if 2 (just was experimenting)
Yes, because now you fail in the second match ("x2" != "x1")
Hm.. strange it managed get success after second compile. At least I glad that it works like I expected in terms of syntax.

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.