Can I make this Scala code snapshot more concise?

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
}
+4
source share
2 answers

How about this:

def toSentiment(sentiment: Int): Sentiment = sentiment match {
    case 0 | 1 ⇒ Sentiment.NEGATIVE
    case 2     ⇒ Sentiment.NEUTRAL
    case 3 | 4 ⇒ Sentiment.POSITIVE
}

Please note that this match is not exhaustive. You can get a runtime error when you run, for example toSentiment(5). Some letters would warn you about this. A safer version (if any other number is neutral) could be:

def toSentiment(sentiment: Int): Sentiment = sentiment match {
    case 0 | 1 ⇒ Sentiment.NEGATIVE
    case 3 | 4 ⇒ Sentiment.POSITIVE
    case _     ⇒ Sentiment.NEUTRAL   
}
+6
source

- :

def toSentiment(sentiment:Int): Sentiment = {
  import Sentiment._
  Vector(NEGATIVE,NEGATIVE,NEUTRAL,POSITIVE,POSITIVE)(sentiment)
}

, , .

: sentiment, , , , , 6.

import Sentiment._ .

+2

Source: https://habr.com/ru/post/1625267/


All Articles