如何在 Scala 中模式匹配数组? [英] How do I pattern match arrays in Scala?

查看:49
本文介绍了如何在 Scala 中模式匹配数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法定义如下

def processLine(tokens: Array[String]) = tokens match { // ...

假设我想知道第二个字符串是否为空

Suppose I wish to know whether the second string is blank

case "" == tokens(1) => println("empty")

不编译.我该怎么做?

推荐答案

如果要对数组进行模式匹配来判断第二个元素是否为空字符串,可以执行以下操作:

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"
}

_* 绑定到任意数量的元素,包括 none.这类似于 Lists 上的以下匹配,它可能更为人所知:

The _* binds to any number of elements including none. This is similar to the following match on Lists, which is probably better known:

def processLine(tokens: List[String]) = tokens match {
  case _ :: "" :: _ => "second is empty"
  case _ => "default"
}

这篇关于如何在 Scala 中模式匹配数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆