在过滤器/映射操作中找不到值

时间:2011-11-10 13:53:50

标签: scala scala-collections

如何修改以下代码段,以便在handleFailure函数中知道“尝试”变量?

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

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

编译器输出=&gt;找不到:值尝试

3 个答案:

答案 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 mapOption上的{{1}}模糊,后者只是在幕后进行匹配。

答案 2 :(得分:1)

怎么样:

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