Is there a way to check for a condition in a map function in scala? I have this list for example:
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.
Now in python this would look something like this:
map(lambda x: 2*x if x % 2 == 0 else x/2, l)
Is there a way to do that in Scala?
You could also write this as a PartialFunction which in some cases is easier to read, especially if you have several conditions:
val result = list.map{
case x if x % 2 == 0 => x * 2
case x => x / 2
}
Yes. if-else
in Scala is a conditional expression, meaning it returns a value. You can use it as follows:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With