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?
Yes, just use parentheses like this (see example below):
However, can’t you use
foreachfor this:Example: