Lorie
Lorie

Reputation: 9

scala returning a Future[Option[user]]

So, I am totally new to Scala, coming from a Java background and have been given a huge scala code base to learn. And, I am very lost and would appreciate any help.

I have the below function that I want to re-arrange. Currently, the function calls two functions in a row and then returns the result. The first function returns a boolean and the second function returns a User. However, what actually should happen is that the second function should only be called if the first function returns true. So, I need to rearrange it to check the return value of the first function before continuing. Every time I rewrite it to do that, I either get a compile error or exception. It is supposed to return a Future[Option[User]] and the first function doesn't return a User. I just want to return None if FunctionA fails, but because it expects Future[Option[X]]], it is unhappy. So, below is the function:

private def profileForCredentials(userId: String, password: String)(implicit ec: ExecutionContext): Future[Option[User]] =
  {
      val credentials: Throwable \/ Boolean = {
      try {
         FunctionA(userId, password).right[Throwable]
      }
      catch {
        case npe: NullPointerException =>
          npe.left[Boolean]
      }
    }

    //This function doesn't need to be called unless credentials=true
    FunctionB(id, userId).map {
        case maybeUser@Some(user) =>
          credentials match {
            case \/-(x) if x =>
              user.some
            case _ =>
              None
          }
        case None =>
          None
      }
}

Upvotes: 1

Views: 122

Answers (1)

Dima
Dima

Reputation: 40510

You guys just got carried away with the scalaz. I am going to bookmark this page to show people at work as an illustration why we should not be using all this fancy stuff.

Just do this:

    Try { 
       FunctionA(userId, password)
    }
    .toOption
    .collect { case(true) => 
      FunctionB(id, userId)
    }
    .getOrElse(Future.value(None))

Upvotes: 3

Related Questions