Scala 警告匹配可能并不详尽

2024-03-19

我对 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 _ => ... )。Option can be Some or None,但你只匹配None case.

If Session.get().getAttribute("player")Some(player)你会得到一个MatchError(例外)。

由于您的代码似乎没有返回任何内容,因此我会在没有match根本没有,只需检查一下isEmpty.

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Scala 警告匹配可能并不详尽 的相关文章

随机推荐