2014-12-30 110 views
6

我對Scala有點新鮮。以下是我的代碼。Scala警告匹配可能不完全

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

我編譯

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

我該如何解決這個問題時,得到下面的警告?有沒有辦法重寫代碼以避免警告?(我正在使用Scala版本2.10.2)

回答

10

當模式匹配,你應該考慮針對所有可能的情況或提供「後備」(案例_ => ...)。 Option可以是SomeNone,但您只能匹配None的情況。

如果Session.get().getAttribute("player")返回Some(player)您將得到MatchError(例外)。

由於您的代碼似乎沒有返回任何內容,因此我會根據match重新編寫此代碼,並且只需檢查isEmpty即可。

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

雖然這與檢查Session.get().getAttribute("player") == null並沒有太大的不同。

+0

謝謝。我將使用你建議的 –

+0

對於樣式,我會'Session.get.getAttr (「foo」)匹配{case null => case _ =>}。更容易閱讀或者選擇(...)或者else alt或者Some(Session.get)過濾器(_.getAttr(「foo 「)!= null)orElse(s => Some(s.setAttr(」「,x)))''或類似的。 –

3

您只匹配案例None,更正確的方法是匹配Some(something)的情況。 Option(...)可以產生NoneSome(_),因此是錯誤。

在這種情況下,較好地解決了你正在嘗試做的,簡直是:

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

您需要包括一個Some情況:

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

但我不需要爲'Some'做任何事情。至少這是我的想法。根據代碼(如果玩家不在那裏,會將玩家添加到會話對象中)應該在'Some(__'case? –

+1

)中完成什麼樣的工作?如果您不需要爲'Some '爲什麼你使用'Option'? –

+0

你只是不必要地創建一個對象來做一個空檢查。 –