加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

这个Scala代码片段可以更简洁吗?

发布时间:2020-12-16 09:51:19 所属栏目:安全 来源:网络整理
导读:我在某个地方看过这个 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} 有没有办法更简
我在某个地方看过这个 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
}

有没有办法更简洁地重写案例陈述?我怀疑如果x == 0 ||必须有一种更简单(更短)的方式表达x 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
}

解决方法

这个怎么样:

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

请注意,此匹配并非详尽无遗.如果运行,可能会出现运行时错误,例如:toSentiment(5).一些短裤会警告你这件事.更安全的版本(假设其他任何数字都是中立的)可以是:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读