Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition in map function

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?

like image 483
Lisa Avatar asked Apr 03 '15 04:04

Lisa


People also ask

How do you condition a function on a map?

To use a condition inside map() in React:Call the map() method on an array. Use a ternary operator to check if the condition is truthy. The operator returns the value to the left of the colon if the condition is truthy, otherwise the value to the right is returned.

How do you write if condition in JSX?

We can embed any JavaScript expression in JSX by wrapping it in curly braces. But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.

Can we use map inside map?

To use a map() inside a map() function in React: Call map() on the outer array, passing it a function. On each iteration, call the map() method on the other array.

How do you use map in React?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.


1 Answers

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) 
like image 51
Ben Reich Avatar answered Oct 25 '22 16:10

Ben Reich