小编paf*_*o00的帖子

列出与其类型匹配的元素

我有一个类似下面的代码:

def walkTree(list:List[Command]) {
    list match {
        case Command1::rest => doSomething(); walkTree(rest)
        case Command2::rest => doSomethingElse(); walkTree(rest)
        case Nil => ;
    }
}
Run Code Online (Sandbox Code Playgroud)

我也知道你可以在特定类型上进行模式匹配并同时分配一个变量:

try {
    ...
}
catch {
    case ioExc:IOException => ioExc.printStackTrace()
    case exc:Exception => throw new RuntimeException("Oh Noes", e);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将两者结合起来如下:

def walkTree(list:List[Command]) {
    list match {
        case cmd1:Command1::rest => doSomething(); walkTree(rest)
        case cmd2:Command2::rest => doSomethingElse(); walkTree(rest)
        case Nil => ;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者我需要在匹配之前提取每个列表元素吗?

scala list pattern-matching

8
推荐指数
1
解决办法
4320
查看次数

标签 统计

list ×1

pattern-matching ×1

scala ×1