如果前面的func回答了某些条件,如何使用for-understanding并跳过运行的func?

问题描述 投票:0回答:1

我在我的mongo dao中创建了3个重复检查,以检查我的数据库中3个不同的重复情况。 (我知道这样做的最好方法是为那些人创建一个复合索引,但不幸的是,这一刻不可能,我需要这些检查)

所以我想这样做,创建这个方法:

  def checkPersonDuplication(person: Person): Future[(ValidationResult, Option[Person])] = for {
    sameSocIdIAndCountryVerification <- {
      logger.info("sameSocIdIAndCountryVerification is running")
      findPersonSameSocIdIAndCountry(person.socId, person.country)
    }
    sameNameAndCountryVerification <- {
      logger.info("sameNameAndCountryVerification is running")
      findPersonSameNameAndCountry(person.name, person.country)
    }
    sameLastNameAndCountryVerification <- {
      logger.info("sameLastNameAndCountryVerification is running")
      findPersonSameByNameAndCountry(person.lname, person.country)
    }
  } yield (sameSocIdIAndCountryVerification, sameNameAndCountryVerification, sameLastNameAndCountryVerification) match {
    case a if a._1.isDefined => (SameSocialSecurityNumberAndCountry, sameSocIdIAndCountryVerification)
    case b if b._2.isDefined => (SameNameAndCountry, sameNameAndCountryVerification)
    case c if c._3.isDefined => (SameLastNameAndCountry, sameLastNameAndCountryVerification)
    case _ => (ValidationSuccess, None)
  }

现在在创建方法中我可以这样做:

 checkPersonDuplication(person) map {res => 
      res._1 match {
        case ValidationSuccess => // do something
        case SameSocialSecurityNumberAndCountry => throw DuplicateInsertion(s"???")
        case SameNameAndCountry => throw DuplicateInsertion(s"???")
        case SameLastNameAndCountry => throw DuplicateInsertion(s"???")
        }
  }

我的问题是如果sameSocIdIAndCountryVerification被定义(因为findPersonSameSocIdIAndCountry返回选项[Person])我不想在for-comprehension中运行其他检查...

所以我试图在每次之后添加“if”,但它会抛出NoSuchElementException。什么是实现这一目标的最佳方法?

scala
1个回答
0
投票

这个版本避免了不必要的验证,但它并不是特别漂亮:

def checkPersonDuplication(person: Person): Future[(ValidationResult, Option[Person])] = {
  logger.info("sameSocIdIAndCountryVerification is running")
  findPersonSameSocIdIAndCountry(person.socId, person.country).flatMap {
    case x@Some(_) =>
      Future.successful((SameSocialSecurityNumberAndCountry, x))
    case None =>
      logger.info("sameNameAndCountryVerification is running")
      findPersonSameNameAndCountry(person.name, person.country).flatMap {
        case x@Some(_) =>
          Future.successful((SameNameAndCountry, x))
        case None =>
          logger.info("sameLastNameAndCountryVerification is running")
          findPersonSameByNameAndCountry(person.lname, person.country).map {
            case x@Some(_) =>
              (SameLastNameAndCountry, x)
            case None =>
              (ValidationSuccess, None)
          }
      }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.