Can't Tell
Can't Tell

Reputation: 13416

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)

Upvotes: 9

Views: 18514

Answers (3)

user908853
user908853

Reputation:

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)
}

Upvotes: 3

Michael Zajac
Michael Zajac

Reputation: 55569

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.

Upvotes: 13

Maurício Linhares
Maurício Linhares

Reputation: 40313

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)
  }
}

Upvotes: 2

Related Questions