Reputation: 13372
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
Upvotes: 2
Views: 7347
Reputation: 15074
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"
}
Upvotes: 4