Scala warning match may not be exhaustive

江枫思渺然 提交于 2019-12-07 03:50:43

问题


I am somewhat new to Scala. Following is my code.

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

I get the following warning when compiling

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

How do I fix this? Is there a way to rewrite the code to avoid the warning?(I am using Scala version 2.10.2)


回答1:


When pattern matching, you should account for all possible cases or provide a "fallback" (case _ => ... ). Option can be Some or None, but you're only matching against the None case.

If Session.get().getAttribute("player") returned Some(player) you would get a MatchError (exception).

Since your code seems to not be returning anything, I would re-write this without the match at all, and just check isEmpty.

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

Though this isn't really much different than checking Session.get().getAttribute("player") == null.




回答2:


You're matching only the case None, a more correct way would be to match the Some(something) case too. Option(...) can yield None or Some(_), hence the error.

In this case a better solution to what you are trying to do would simply be:

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



回答3:


You need to include a Some case:

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


来源:https://stackoverflow.com/questions/27709101/scala-warning-match-may-not-be-exhaustive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!