0
\$\begingroup\$

I have a function like this

def findById(id: UUID): Future[Option[Item]]

case class Item(subject: String)

Now I want to retrieve the subject if the item exists else I want the subject to be empty string.

val subject: Future[String] = repository
  .findById(someId)
  .map(_.map(i => i.subject))
  .map(_.getOrElse(""))

subject.foreach(doSomething)

Am I doing it right or is there a better way in Scala without frameworks like Scalaz.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does \$\endgroup\$ – Dannnno May 23 '18 at 13:45
1
\$\begingroup\$

It's better that you are staying in the Futures domain, no longer trying to unwrap to String.

It's not so easy to follow all of the underscore-based function expressions. I'd try something like...

val subject: Future[String] = {
  repository.findById(someId) map { mbItem =>
    mbItem match {
      case Some( item ) => item.subject
      case None         => ""
    }
  }
}
\$\endgroup\$
0
\$\begingroup\$

It's best to stay in the Futures domain if you can. But if you absolutely need out, you need to await to be sure a result has been computed.

val result = Await.result(repository.findById(someId), Duration.Inf)
val subject = result match {
   case Some( item ) => item.subject
   case None         => ""
}

(If you prefer not to wait, but you are cool with the computation maybe not having completed, see the value method of Future.)

\$\endgroup\$
  • \$\begingroup\$ I thought the map applies a function on the future when it completes. Isn't the Await.result also blocking? \$\endgroup\$ – uraza May 23 '18 at 9:19
  • \$\begingroup\$ My apologies, sir. I forgot to add a foreach at the end. See edited post. \$\endgroup\$ – uraza May 23 '18 at 9:22
  • \$\begingroup\$ yes, await is blocking. but in the original version of your post subject was a String rather than Future[String], so you would have had to block to safely unwrap. now that what you want is Future[String], you can stay in the Futures domain with map(...) etc. \$\endgroup\$ – Steve Waldman May 23 '18 at 10:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.