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
?
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.
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.
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.
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.
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)
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