簡體   English   中英

Scala模式匹配嵌套案例

[英]scala pattern matching nested cases

應用某些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中的異常:scala.Function0 $ class.apply $ mcV $ sp(patternMatchingTest $ delayedInit $ body.apply(PatternMatchingTest.scala:32)處的x2(patternMatchingTest.scala:32)在scala.runtime.AbstractFunction0.apply $ mcV $ sp(AbstractFunction0.scala:12)在scala.App $$ anonfun $ main $ 1.apply(App.scala:71)在scala.App $$ anonfun $主要$ 1.適用

您遇到的問題是示例輸入( val x1 = 1 )與您給出的一種情況不匹配(因為x1不大於1)。 您將需要修改現有的大小寫(例如,將if更改為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"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM