scala模式匹配嵌套案例

时间:2013-09-09 23:48:27

标签: scala pattern-matching

在应用了match之后,我尝试case。有点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)

它因scala.MatchError例外而失败。

有可能吗?我似乎看到了类似的东西。

  

线程“main”中的异常scala.MatchError:x2(类   java.lang.String)at   pattern_matching.PatternMatchingTest $ delayedInit $ body.apply(PatternMatchingTest.scala:32)     在scala.Function0 $ class.apply $ mcV $ sp(Function0.scala:40)at   scala.runtime.AbstractFunction0.apply $ MCV $ SP(AbstractFunction0.scala:12)     在scala.App $$ anonfun $ main $ 1.apply(App.scala:71)at   scala.App $$ anonfun $ $主1.适用

1 个答案:

答案 0 :(得分:4)

您遇到的问题是您的示例输入(val x1 = 1)与您给出的一个案例不匹配(因为x1不大于1)。您需要修改现有案例(例如,将if更改为if(x >= 1)之类的内容)或添加至少一个案例,并且应该考虑默认案例。例如:

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"
}
相关问题