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

Can*_*ell 6 scala compiler-warnings

我对Scala有些新意.以下是我的代码.

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

编译时我收到以下警告

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

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

Mic*_*jac 10

在模式匹配时,您应考虑所有可能的情况或提供"后备"(case _ => ...).Option可以是SomeNone,但你只是匹配None案件.

如果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)
}
Run Code Online (Sandbox Code Playgroud)

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