How to use Future[Option] in Scala

1,374 views
Skip to first unread message

Anil Mathew

unread,
Jan 20, 2017, 11:44:56 AM1/20/17
to scala-user
Hi,

  I have a scala application which uses the Slick 3.x for the DB calls. Since all the Slick 3 calls are Async, it returns the Future[Option].

  So I am trying to get the result from a DB call and use that data to do other things. i.e
  
  My DB class has the following code:
  
      // Method to get the User record by username
    def getUserByUsername(username: String): Future[Option[User]] = {
        val query = userData.filter(user => user.username === username)
        val action = query.result.headOption
        db.run(action)
    }
   In my controller, I call the above method and i wanted to use the returned 'User' data for other calls. Can someone please help me how do I do this?


Thanks

Vlad Patryshev

unread,
Jan 20, 2017, 12:23:37 PM1/20/17
to Anil Mathew, scala-user
The call does not return a User. If you want to apply functions to the value(s) inside, the right solution would be either to use Scala loops, or to use map method, every monad (e.g. Future, Option) has it.

Thanks,
-Vlad

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Udas

unread,
Jan 22, 2017, 10:06:06 PM1/22/17
to scala-user
Vlad is correct. Perhaps you can use the below code as a starting point (copy paste into scala console and play with it).

import scala.concurrent._
import ExecutionContext.Implicits.global
def getUserByUserName(n: String): Future[Option[String]] = Future.successful(Some(n))

def processUser(username: String): Future[Unit] = {
   for {
     optionalUser <- getUserByUserName(username)
     _ = optionalUser map { user =>
        print(s"User is here: ${user}\n")
        // Do whatever you need to do, but say you call a function that is Unit
     } getOrElse {
        print(s"User not found for ${username}\n")
     }
  } yield()
}

val f = processUser("a")
f.value


Hope that helps,
Udas

Lanny Ripple

unread,
Jan 25, 2017, 3:15:25 PM1/25/17
to scala-user
When I work with Play and Databases I really like the technique described by Erik Bakker here

Options in Futures, how to unsuck them
Reply all
Reply to author
Forward
0 new messages