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

Scala警告匹配可能并非详尽无遗

发布时间:2020-12-16 19:10:14 所属栏目:安全 来源:网络整理
导读:我对 Scala有些新意.以下是我的代码. Option(Session.get().getAttribute("player")) match { case None = { val player = new Player(user.getEmail,user.getNickname).createOrGet Session.get().setAttribute("player",player) }} 编译时我收到以下警告 W
我对 Scala有些新意.以下是我的代码.

Option(Session.get().getAttribute("player")) match {
  case None => {
    val player = new Player(user.getEmail,user.getNickname).createOrGet
    Session.get().setAttribute("player",player)
  }
}

编译时我收到以下警告

Warning:(35,11) match may not be exhaustive.
It would fail on the following input: Some(_)
    Option(Session.get().getAttribute("player")) match {
          ^

我该如何解决?有没有办法重写代码以避免警告?(我使用的是Scala版本2.10.2)

解决方法

在模式匹配时,您应考虑所有可能的情况或提供“后备”(case _ => …).选项可以是Some或None,但您只能匹配None case.

如果Session.get().getAttribute(“player”)返回Some(播放器),则会得到MatchError(异常).

由于你的代码似乎没有返回任何东西,我会在没有匹配的情况下重写它,只需检查isEmpty.

if(Option(Session.get().getAttribute("player")).isEmpty) {
    val player = new Player(user.getEmail,player)
}

虽然这与检查Session.get()没有太大的不同.getAttribute(“player”)== null.

(编辑:李大同)

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

    推荐文章
      热点阅读