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)
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
.
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)
}
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With