scala 如何匹配多个参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5392922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I match multiple arguments?
提问by Phil H
I have a function:
我有一个功能:
def func(a: int, b: int, c: double): int
And I want to match various possible scenarios
我想匹配各种可能的场景
- Wherever
cis 0, returnb-a - Wherever
c> 9, return 0 - Wherever
a=breturn 0
- 哪里
c为0,返回b-a - 当
c> 9 时,返回 0 - 哪里都
a=b返回0
And so on, before doing some more complex logic if none of the above are satisfied.
依此类推,如果以上都不满足,则在做一些更复杂的逻辑之前。
Do I have to match c separately first, or can I match on a,b,c, like _,_,0?
我必须先分别匹配 c ,还是可以匹配 a,b,c 之类的_,_,0?
回答by tenshi
You can pattern match all described cases like this:
您可以像这样模式匹配所有描述的案例:
def func(a: Int, b: Int, c: Double) = (a, b, c) match {
case (a, b, 0) => b - a
case (a, b, c) if c > 9 || a == b => 0
case _ => 1 // add your logic here
}
回答by The Archetypal Paul
Following on from my comments to Easy Angel's answer, I still feel this
继我对 Easy Angel 的回答发表评论后,我仍然感觉到这一点
if (c == 0)
b -a
else if (c > 9)
0
else if (a == b)
0
else
1 // your logic here
is clearer. Basically because there isn't really any pattern to match here.
更清楚。基本上是因为这里没有任何模式可以匹配。

