2014-12-30 2 views
6

저는 스칼라에 다소 익숙합니다. 다음은 내 코드입니다. 나는이 문제를 해결하려면 어떻게스칼라 경고 일치가 완전하지 않을 수도 있습니다.

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

를 컴파일 할 때

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

나는 다음과 같은 경고를 얻을? 경고를 피하기 위해 코드를 다시 작성하는 방법이 있습니까? (스칼라 버전 2.10.2를 사용 중입니다.)

답변

10

하는 패턴 매칭, 당신은 고려해야합니다 : 당신은 Some 경우를 포함 할 필요가

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

고마워요. 당신이 제안한 것을 사용할 것입니다. –

+0

스타일에 대해서는'Session.get.getAttr (옵션) (...) orElse alt' 또는'Some (Session.get) filter (_.getAttr ("foo") foo ")! = null) orElse (s => Some (s.setAttr (" ", x))) 또는 이와 유사합니다. –

3

None과 일치하는 경우보다 정확한 방법으로 Some(something)도 일치시킬 수 있습니다. Option(...)None 또는 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) 
    } 
} 
1

을 모든 가능한 경우에 대해 또는 "대체 (fallback)"(case _ => ...)를 제공하십시오. OptionSome 또는 None 일 수 있지만 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

하지만 'Some'경우에는 아무 것도 할 필요가 없습니다. 적어도 그것이 내가 생각하는 것입니다. 코드를 기반으로 (세션 객체에 세션 객체를 추가하는 경우), Some (__)의 경우 어떤 종류의 작업을 수행해야합니까? –

+1

'Some '왜'Option'을 사용하고있는 것입니까? –

+0

널 체크를하기 위해 객체를 불필요하게 생성하고 있습니다. –

관련 문제