scala 如果地图功能中的条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39621389/
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
If condition in map function
提问by dumm3rjung3
Is there a way to check for a condition in a map function in scala? I have this list for example:
有没有办法在 Scala 中检查地图函数中的条件?例如,我有这个列表:
List(1,2,3,4,5,6)
and I want all the even numbers to be mulitplied by 2 and all the odd numbers to be divided by 2.
我希望所有偶数都乘以 2,所有奇数除以 2。
Now in python this would look something like this:
现在在 python 中,这看起来像这样:
map(lambda x: 2*x if x % 2 == 0 else x/2, l)
Is there a way to do that in Scala?
有没有办法在 Scala 中做到这一点?
回答by Yuval Itzchakov
Yes. if-elsein Scala is a conditional expression, meaning it returns a value. You can use it as follows:
是的。if-else在 Scala 中是一个条件表达式,这意味着它返回一个值。您可以按如下方式使用它:
val result = list.map(x => if (x % 2 == 0) x * 2 else x / 2)
Which yields:
其中产生:
scala> val list = List(1,2,3,4,5,6)
list: List[Int] = List(1, 2, 3, 4, 5, 6)
scala> list.map(x => if (x % 2 == 0) x * 2 else x / 2)
res0: List[Int] = List(0, 4, 1, 8, 2, 12)
回答by Idan Waisman
You could also write this as a PartialFunction which in some cases is easier to read, especially if you have several conditions:
你也可以把它写成一个 PartialFunction ,它在某些情况下更容易阅读,特别是如果你有几个条件:
val result = list.map{
case x if x % 2 == 0 => x * 2
case x => x / 2
}

