如何修改以下代码段,以便在handleFailure函数中知道“尝试”变量?
def getLoginAttempts(username: String): Option[Long] = ...
getLoginAttempts(username) filter (attempts => attempts <= MAX_ATTEMPTS) map {
handleFailure(username, attempts)
} orElse sendNotification()
编译器输出=&gt;找不到:值尝试
答案 0 :(得分:3)
为什么不简单:
getLoginAttempts(username) filter (attempts => attempts <= MAX_ATTEMPTS) map { attempts =>
handleFailure(username, attempts)
} orElse sendNotification()
或许我不明白什么是handleFailure?
答案 1 :(得分:2)
使用模式匹配可以更明确地表达。
getLoginAttempts(username) match {
case Some(attempts) if attempts <= MAX_ATTEMPTS => handleFailure(username, attempts)
case _ => sendNotification()
}
如果您希望将None
案例与Some(attempts), attempts > MAX_ATTEMPTS
案例区分开来,这也可以在以后轻松实现。恕我直言,模式匹配不如filter
map
和Option
上的{{1}}模糊,后者只是在幕后进行匹配。
答案 2 :(得分:1)
怎么样:
val attempts = getLoginAttempts(username).getOrElse(0)
if(attempts >= MAX_ATTEMPTS) handleFailure(username, attempts) else sendNotifications()