Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala warning match may not be exhaustive

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)

like image 202
Can't Tell Avatar asked Dec 30 '14 16:12

Can't Tell


3 Answers

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.

like image 191
Michael Zajac Avatar answered Oct 15 '22 22:10

Michael Zajac


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)
}
like image 22
Peter Avatar answered Oct 15 '22 23:10

Peter


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)
  }
}
like image 26
Maurício Linhares Avatar answered Oct 15 '22 22:10

Maurício Linhares