Can this Scala code snippet be made more concise? -


i've seen 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 way rewrite case statement more concisely? suspect there must simpler (shorter) way express x if x == 0 || x == 1 condition.

by way, 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 i'm looking for. i'm hoping 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 this:

def tosentiment(sentiment: int): sentiment = sentiment match {     case 0 | 1 ⇒ sentiment.negative     case 2     ⇒ sentiment.neutral     case 3 | 4 ⇒ sentiment.positive } 

note match not exhaustive. runtime error if run, example: tosentiment(5). linters warn this. safer version (assumming other number neutral) be:

def tosentiment(sentiment: int): sentiment = sentiment match {     case 0 | 1 ⇒ sentiment.negative     case 3 | 4 ⇒ sentiment.positive     case _     ⇒ sentiment.neutral    } 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -