【问题标题】:scala pattern matching nested casesscala模式匹配嵌套案例
【发布时间】:2013-09-13 13:30:12
【问题描述】:

在申请了一些case 之后,我尝试match。有点像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 异常而失败。

有可能吗?我好像见过类似的东西。

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

【问题讨论】:

    标签: scala pattern-matching


    【解决方案1】:

    您遇到的问题是您的示例输入 (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"
    }
    

    【讨论】:

    • 即使2(只是在试验)
    • 是的,因为现在你在第二场比赛中失败了 ("x2" != "x1")
    • 嗯.. 奇怪的是,它在第​​二次编译后成功了。至少我很高兴它在语法方面像我预期的那样工作。
    猜你喜欢
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2011-08-11
    • 2017-12-16
    • 2014-08-12
    相关资源
    最近更新 更多