Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this Scala code snippet be made more concise?

Tags:

scala

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
}
like image 953
Paul Jurczak Avatar asked Feb 07 '23 23:02

Paul Jurczak


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
}

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   
}
like image 158
gilad hoch Avatar answered Feb 10 '23 14:02

gilad hoch


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.

like image 43
Eduardo Avatar answered Feb 10 '23 12:02

Eduardo