列出与其类型匹配的元素
我有一个类似于下面的代码:
def walkTree(list:List[Command]) {
list match {
case Command1::rest => doSomething(); walkTree(rest)
case Command2::rest => doSomethingElse(); walkTree(rest)
case Nil => ;
}
}
我还知道您可以对特定类型进行模式匹配并同时分配一个变量:
try {
...
}
catch {
case ioExc:IOException => ioExc.printStackTrace()
case exc:Exception => throw new RuntimeException("Oh Noes", e);
}
有没有一种方法可以将两者结合起来,如下所示:
def walkTree(list:List[Command]) {
list match {
case cmd1:Command1::rest => doSomething(); walkTree(rest)
case cmd2:Command2::rest => doSomethingElse(); walkTree(rest)
case Nil => ;
}
}
或者我需要提取每个匹配之前列出元素?
I've got a code similar to one below:
def walkTree(list:List[Command]) {
list match {
case Command1::rest => doSomething(); walkTree(rest)
case Command2::rest => doSomethingElse(); walkTree(rest)
case Nil => ;
}
}
I also know that you can pattern match on specific type and assign a variable at the same time:
try {
...
}
catch {
case ioExc:IOException => ioExc.printStackTrace()
case exc:Exception => throw new RuntimeException("Oh Noes", e);
}
Is there a way to combine both in something like below:
def walkTree(list:List[Command]) {
list match {
case cmd1:Command1::rest => doSomething(); walkTree(rest)
case cmd2:Command2::rest => doSomethingElse(); walkTree(rest)
case Nil => ;
}
}
Or do I need to extract each list element before matching?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,只需使用这样的括号(参见下面的示例):
但是,您不能使用
foreach
来实现此目的:示例:
Yes, just use parentheses like this (see example below):
However, can't you use
foreach
for this:Example:
使用
foreach
然后对每个元素进行模式匹配对我来说似乎更清晰:Using
foreach
and then pattern match on each element seems to be clearer for me: