如何在 Scala 中模式匹配数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6647166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I pattern match arrays in Scala?
提问by deltanovember
My method definition looks as follows
我的方法定义如下
def processLine(tokens: Array[String]) = tokens match { // ...
Suppose I wish to know whether the second string is blank
假设我想知道第二个字符串是否为空
case "" == tokens(1) => println("empty")
Does not compile. How do I go about doing this?
不编译。我该怎么做?
回答by Ruediger Keller
If you want to pattern match on the array to determine whether the second element is the empty string, you can do the following:
如果要对数组进行模式匹配以确定第二个元素是否为空字符串,可以执行以下操作:
def processLine(tokens: Array[String]) = tokens match {
case Array(_, "", _*) => "second is empty"
case _ => "default"
}
The _*binds to any number of elements including none. This is similar to the following match on Lists, which is probably better known:
将_*结合到任何数量的元件,包括无。这类似于 Lists 上的以下匹配项,它可能更为人所知:
def processLine(tokens: List[String]) = tokens match {
case _ :: "" :: _ => "second is empty"
case _ => "default"
}
回答by synapse
What is extra cool is that you can use an alias for the stuff matched by _*with something like
更酷的是,您可以为匹配的内容使用别名,_*例如
val lines: List[String] = List("Alice Bob Carol", "Bob Carol", "Carol Diane Alice")
lines foreach { line =>
line split "\s+" match {
case Array(userName, friends@_*) => { /* Process user and his friends */ }
}
}
回答by paradigmatic
Pattern matching may not be the right choice for your example. You can simply do:
模式匹配可能不是您示例的正确选择。你可以简单地做:
if( tokens(1) == "" ) {
println("empty")
}
Pattern matching is more approriate for cases like:
模式匹配更适用于以下情况:
for( t <- tokens ) t match {
case "" => println( "Empty" )
case s => println( "Value: " + s )
}
which print something for each token.
为每个令牌打印一些东西。
Edit:if you want to check if there exist any token which is an empty string, you can also try:
编辑:如果你想检查是否存在任何空字符串的令牌,你也可以尝试:
if( tokens.exists( _ == "" ) ) {
println("Found empty token")
}
回答by missingfaktor
casestatement doesn't work like that. That should be:
case声明不能那样工作。那应该是:
case _ if "" == tokens(1) => println("empty")

