2011-08-26 82 views
69

比方说,我想使用相同的代码处理来自远程服务的多个返回值。我不知道如何在斯卡拉表达这样的:如何在Scala中匹配多个值?

code match { 
    case "1" => // Whatever 
    case "2" => // Same whatever 
    case "3" => // Ah, something different 
} 

我知道我可以使用提取方法和调用,但还是有重复呼叫。如果我使用红宝石,我会写这样的:

case code 
when "1", "2" 
    # Whatever 
when "3" 
    # Ah, something different 
end 

注意,我简单的例子,所以我不想对正则表达式或一些这样的模式匹配。匹配值实际上是复杂的值。

+0

可能重复阶(http://stackoverflow.com/questions/1837754/match-multiple-cases-classes-in-scala) – nawfal

回答

116

你可以这样做:

,你不能绑定模式名称的部分
code match { 
    case "1" | "2" => // whatever 
    case "3" => 
} 

注 - 你不能做到这一点目前:

code match { 
    case Left(x) | Right(x) => 
    case null => 
} 
在[匹配多例类的