2011-11-10 2 views
1

handleFailure 함수에서 "attempt"변수를 알 수 있도록 다음 코드를 수정할 수 있습니까?필터/맵 작업에서 값을 찾을 수 없습니다.

def getLoginAttempts(username: String): Option[Long] = ... 

getLoginAttempts(username) filter (attempts => attempts <= MAX_ATTEMPTS) map { 
    handleFailure(username, attempts) 
} orElse sendNotification() 

컴파일러 출력 => 찾을 수 없음 : 왜 단순히

val attempts = getLoginAttempts(username).getOrElse(0) 
if(attempts >= MAX_ATTEMPTS) handleFailure(username, attempts) else sendNotifications() 

답변

3

:

getLoginAttempts(username) filter (attempts => attempts <= MAX_ATTEMPTS) map { attempts => 
    handleFailure(username, attempts) 
} orElse sendNotification() 

아니면 내가 handleFailure 무엇을 이해하지 못하는 값은

1

Howabout 시도 ?

2

이것은 패턴 일치로 더 명확하게 표현됩니다.

getLoginAttempts(username) match { 
    case Some(attempts) if attempts <= MAX_ATTEMPTS => handleFailure(username, attempts) 
    case _ => sendNotification() 
} 

도 쉽게 나중에 당신이 Some(attempts), attempts > MAX_ATTEMPTS 케이스에서 None 경우를 구별하고자하는 경우를합니다. IMHO의 패턴 매칭은 filtermapOption 값보다 덜 흐릿합니다. 이는 간단히 장면 뒤에서 일치를 수행합니다.

관련 문제