我已經看到了這個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
}
這已經很簡潔了,你的意思是明確的:D – Mathemats
這是一個非常有趣的問題Paul,但我認爲你可能會在http://codereview.stackexchange.com/上得到更好的答案 – eliasah
@Mathemats我編輯了我的問題我只是注意到吉拉德的回答,這正是我想到的。 –