[英]Why does pattern matching in Scala not work with variables?
取以下function:
def fMatch(s: String) = {
s match {
case "a" => println("It was a")
case _ => println("It was something else")
}
}
這種模式很好地匹配:
scala> fMatch("a")
It was a
scala> fMatch("b")
It was something else
我希望能夠做的是以下幾點:
def mMatch(s: String) = {
val target: String = "a"
s match {
case target => println("It was" + target)
case _ => println("It was something else")
}
}
這會發出以下錯誤:
fMatch: (s: String)Unit
<console>:12: error: unreachable code
case _ => println("It was something else")
我猜這是因為它認為目標實際上是您想要分配給任何輸入的名稱。 兩個問題:
為什么會有這種行為? 不能僅在 scope 中查找具有適當類型的現有變量並首先使用這些變量,如果沒有找到,則將目標視為模式匹配的名稱?
有解決方法嗎? 有什么方法可以對變量進行模式匹配? 最終可以使用一個大的 if 語句,但 match case 更優雅。
您正在尋找的是一個穩定的標識符。 在 Scala 中,這些必須以大寫字母開頭,或者被反引號包圍。
這兩種方法都可以解決您的問題:
def mMatch(s: String) = {
val target: String = "a"
s match {
case `target` => println("It was" + target)
case _ => println("It was something else")
}
}
def mMatch2(s: String) = {
val Target: String = "a"
s match {
case Target => println("It was" + Target)
case _ => println("It was something else")
}
}
為了避免意外引用封閉 scope 中已經存在的變量,我認為默認行為是小寫模式是變量而不是穩定的標識符是有道理的。 只有當您看到以大寫或反引號開頭的內容時,您才需要注意它來自周圍的 scope。
您也可以將其分配給案例內的臨時變量,然后進行比較,這也可以
def mMatch(s: String) = {
val target: String = "a"
s match {
case value if (value ==target) => println("It was" + target) //else {} optional
case _ => println("It was something else")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.