Scala warning may not be comprehensive

I am a little new to Scala. Below 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) } } 

At compilation

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

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

+6
source share
3 answers

When comparing with samples, you should consider all possible cases or provide a “backup copy” (case _ => ...). Option can be Some or None , but you only match the None case.

If Session.get().getAttribute("player") returns Some(player) , you will receive a MatchError (exception).

Since your code does not seem to return anything, I would rewrite it without match 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) } 

Although this is not much different from checking Session.get().getAttribute("player") == null .

+10
source

You correspond only to the None case, the Some(something) case will correspond in a more correct way. Option(...) may give None or Some(_) , hence an error.

In this case, the best solution for what you are trying to do is simply:

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

You need to enable the 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) } } 
+1
source

Source: https://habr.com/ru/post/980322/


All Articles