2016-01-21 80 views
4

我已經看到了這個Scala代碼段某處:這個Scala代碼片斷可以更簡潔嗎?

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 
} 

有沒有辦法更簡潔改寫case聲明?我懷疑必須有一種更簡單(更短)的方式來表達x if x == 0 || x == 1條件。

順便說一句,這種形式:

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 
} 

是不是我要找的。我希望這樣的事情:

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 
} 

甚至:

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

這已經很簡潔了,你的意思是明確的:D – Mathemats

+0

這是一個非常有趣的問題Paul,但我認爲你可能會在http://codereview.stackexchange.com/上得到更好的答案 – eliasah

+0

@Mathemats我編輯了我的問題我只是注意到吉拉德的回答,這正是我想到的。 –

回答

6

如何:

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

請注意,這場比賽並不詳盡。如果運行,您可能會遇到運行時錯誤,例如:toSentiment(5)。有些棉絨會警告你這件事。一個更安全的版本(assumming任何其他數字將是中性的)可能是:

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

謝謝,這正是我所希望的。 –

+0

當然,np :)順便說一句,它可能會對這個簡單的用例來說是一種矯枉過正,但是你可能會發現[精煉](https://github.com/fthomas/refined)對更復雜的數字範圍檢查有幫助。 –

2

你可以這樣做:

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

佔用更少的字符,但我不認爲是更好的。

我會:檢查範圍sentiment,它可以使這個功能,和原來的,拋出一個例外,如果它是6,例如。

使用import Sentiment._可以爲您節省一些冗長。