If condition in map function

14,002

Solution 1

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)

Solution 2

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
}
Share:
14,002
dumm3rjung3
Author by

dumm3rjung3

Updated on June 18, 2022

Comments

  • dumm3rjung3
    dumm3rjung3 almost 2 years

    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?