Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition in map function

Tags:

list

scala

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?

like image 621
dumm3rjung3 Avatar asked Sep 21 '16 16:09

dumm3rjung3


2 Answers

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
}
like image 95
Idan Waisman Avatar answered Nov 09 '22 18:11

Idan Waisman


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)
like image 26
Yuval Itzchakov Avatar answered Nov 09 '22 19:11

Yuval Itzchakov