Reputation: 1507
How can I modify the following code snippet so that the "attempts" variable is known in the handleFailure function?
def getLoginAttempts(username: String): Option[Long] = ...
getLoginAttempts(username) filter (attempts => attempts <= MAX_ATTEMPTS) map {
handleFailure(username, attempts)
} orElse sendNotification()
compiler output => not found: value attempts
Upvotes: 1
Views: 469
Reputation: 53725
This would be more clearly expressed with pattern matching.
getLoginAttempts(username) match {
case Some(attempts) if attempts <= MAX_ATTEMPTS => handleFailure(username, attempts)
case _ => sendNotification()
}
This also makes it easy later on if you wish to distinguish the None
case from the Some(attempts), attempts > MAX_ATTEMPTS
case. IMHO, pattern matching is less obscure than filter
and map
on Option
values, which simply perform the matching behind the scenes.
Upvotes: 2
Reputation: 3616
Why not simply:
getLoginAttempts(username) filter (attempts => attempts <= MAX_ATTEMPTS) map { attempts =>
handleFailure(username, attempts)
} orElse sendNotification()
Or maybe I don't understand what is handleFailure?
Upvotes: 3
Reputation: 12268
Howabout :
val attempts = getLoginAttempts(username).getOrElse(0)
if(attempts >= MAX_ATTEMPTS) handleFailure(username, attempts) else sendNotifications()
Upvotes: 1