将带有 if 和 else 子句的嵌套平面图表达式重写为 for 理解

Rewrite a nested flatmap expression with an if and else clause to a for comprehension

考虑以下嵌套平面图结构:

val isValid: F[Boolean] = userRepository.isValid(username, password)

isValid.flatMap(valid =>
  if (valid) {
    userRepository.getClaims(username).flatMap(claims => {
      val token = JWTRefreshService.createToken(claims)
      Created(token)
    }
   )
  } else {
      Unauthorized(headers.`WWW-Authenticate`(NonEmptyList.of(Challenge(scheme = "Bearer", realm =
      "Access to authorize a request"))))
    }
  )

其中 FF[_] : Sync

我怎样才能将这个结构重写成for-comprehension。我不知道如何在不创建嵌套 for-comprehension 的情况下重写 if else 子句。

我会选择这样的东西:

for {
  isValid <- userRepository.isValid(username, password)
  validation <- if (isValid) createToken(username)
                else
                  Unauthorized(
                    headers.`WWW-Authenticate`(
                      NonEmptyList.of(Challenge(scheme = "Bearer", realm = "Access to authorize a request"))
                  )
                )
} yield validation

def createToken[F: Sync](username: String): F[YourADT] = for {
  claims <- userRepository.getClaims(username)
  token  <- JWTRefreshService.createToken(claims)
} yield Created(token)