Scala警告匹配可能并不详尽 [英] Scala warning match may not be exhaustive

查看:216
本文介绍了Scala警告匹配可能并不详尽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Scala有点陌生。以下是我的代码。

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

编译时会收到以下警告

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)

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)

推荐答案

何时模式匹配,则应考虑所有可能的情况或提供一个后备(case _ => ...)。 选项可以是某些,但是您仅与情况匹配。

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.

如果 Session.get()。getAttribute( player)返回 Some(玩家),您会得到 MatchError (例外)。

If Session.get().getAttribute("player") returned Some(player) you would get a MatchError (exception).

因为您的代码似乎为了不返回任何内容,我将完全不使用 match 重写它,然后检查 isEmpty

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

尽管这与检查 Session.get()。getAttribute( player)== null

这篇关于Scala警告匹配可能并不详尽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆