I've seen this Scala code snippet somewhere:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case x if x == 0 || x == 1 => Sentiment.NEGATIVE
case 2 => Sentiment.NEUTRAL
case x if x == 3 || x == 4 => Sentiment.POSITIVE
}
Is there a way to rewrite the case
statement more concisely? I suspect there must be a simpler (shorter) way to express x if x == 0 || x == 1
condition.
By the way, this form:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case 0 => Sentiment.NEGATIVE
case 1 => Sentiment.NEGATIVE
case 2 => Sentiment.NEUTRAL
case 3 => Sentiment.POSITIVE
case 4 => Sentiment.POSITIVE
}
is not what I'm looking for. I'm hoping for something like this:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case x in {0, 1} => Sentiment.NEGATIVE
case 2 => Sentiment.NEUTRAL
case x in {3, 4} => Sentiment.POSITIVE
}
or even:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case 0, 1 => Sentiment.NEGATIVE
case 2 => Sentiment.NEUTRAL
case 3, 4 => Sentiment.POSITIVE
}
How about this:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case 0 | 1 ⇒ Sentiment.NEGATIVE
case 2 ⇒ Sentiment.NEUTRAL
case 3 | 4 ⇒ Sentiment.POSITIVE
}
Note that this match is not exhaustive. You could get a runtime error if you run, for example: toSentiment(5)
. Some linters would warn you about this. A safer version (assumming any other number would be neutral) could be:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case 0 | 1 ⇒ Sentiment.NEGATIVE
case 3 | 4 ⇒ Sentiment.POSITIVE
case _ ⇒ Sentiment.NEUTRAL
}
You could do something like:
def toSentiment(sentiment:Int): Sentiment = {
import Sentiment._
Vector(NEGATIVE,NEGATIVE,NEUTRAL,POSITIVE,POSITIVE)(sentiment)
}
which occupies less characters, but which I do not think is better.
I would: check the range of sentiment
, which could make this function, and the original one, throw an exception if it were 6, for example.
Using import Sentiment._
can save you some verbosity.
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