I saw 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 it possible to rewrite the instruction more briefly case? I suspect there should be a simpler (shorter) way to express the condition x if x == 0 || x == 1.
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
}
not what i'm looking for. I hope 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
}
source
share