Condition in map function

Lisa picture Lisa · Apr 3, 2015 · Viewed 37.9k times · Source

Is there anything in Scala like,

condition ? first_expression : second_expression;

that I can use within map function in scala? I want to be able to write something like this:

val statuses = tweets.map(status => status.isTruncate? //do nothing | status.getText())

If the inline function is not possible, how can I write a condition within map?

Answer

Ben Reich picture Ben Reich · Apr 3, 2015

The ? operator, sometimes called the ternary operator is not necessary in Scala, since it is subsumed by a regular if-else expression:

val x = if (condition) 1 else 2

To use this in a map, you can use flatMap and then return an Option on either side of the if-else. Since Option is implicitly convertible to Iterable, the effect is that the list is flattened, and the Nones are filtered:

val statuses = tweets.flatMap(status => if (status.isTruncate) None else Some(status.getText))

This is equivalent to using map and then flatten:

val statuses = tweets.map(status => if (status.isTruncate) None else Some(status.getText)).flatten

More idiomatically, you can use collect, which allows you to filter and map in one step using a partial function:

val statuses = tweets.collect {
    case status if !status.isTruncate => status.getText
}

You can also do this in 2 steps using filter and map:

val statuses = tweets.filterNot(_.isTruncate).map(_.getText)

The downside here is that this will iterate over the list twice, which may be undesirable. If you use view, you can use this same logic and only iterate over the list once:

val statuses = tweets.view.filterNot(_.isTruncate).map(_.getText)