我在某个地方看过这个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
}
Run Code Online (Sandbox Code Playgroud)
有没有办法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
}
Run Code Online (Sandbox Code Playgroud)
不是我想要的.我希望这样的事情:
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
}
Run Code Online (Sandbox Code Playgroud)
甚至:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case 0, 1 => Sentiment.NEGATIVE
case 2 => Sentiment.NEUTRAL
case 3, 4 => Sentiment.POSITIVE
}
Run Code Online (Sandbox Code Playgroud)
这个怎么样:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case 0 | 1 ? Sentiment.NEGATIVE
case 2 ? Sentiment.NEUTRAL
case 3 | 4 ? Sentiment.POSITIVE
}
Run Code Online (Sandbox Code Playgroud)
请注意,此匹配并非详尽无遗.如果运行,可能会出现运行时错误,例如:toSentiment(5).一些短裤会警告你这件事.更安全的版本(假设其他任何数字都是中立的)可以是:
def toSentiment(sentiment: Int): Sentiment = sentiment match {
case 0 | 1 ? Sentiment.NEGATIVE
case 3 | 4 ? Sentiment.POSITIVE
case _ ? Sentiment.NEUTRAL
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |