简体   繁体   中英

Scala, how to use Some(value) from an Option implicitly?

I have a piece of code that extracts a string from a request body, but it may not be there, so it is an Option[String] . If there is a value, then I wish to use it implicitly.

To do this conversion, I write implicit val code = googleCode .

Is there a way to make googleCode an implicit String so that I can use it directly rather than creating an implicit val with the value of googleCode ?

    request.getQueryString("code") match {
      case None => 
        Logger.error("unable to retrieve authentication code from google request")
        Redirect(routes.Application.index())

      case Some(googleCode) => Async {
        implicit val code: String = googleCode // <== CONVERTING TO AN IMPLICIT
        Logger.debug("retrieved authentication code, proceeding to get token")
        ...
        Ok("congratulations, ${user.name}, you are logged in!")

Note, the code snippet is from a Playframework Controller, but this is more a question of the Scala language in general

It's often advisable to avoid using pattern matching with Options anyway. Here's how you can write it:

request.getQueryString("code") map { implicit googleCode =>
  // googleCode is an implicit String! do something with it
} getOrElse {
  // handle the None case
}

Hmm. Instead of looking for a solution for converting a code using Option into some kind of Java, I would suggest to take these three easy steps.

Step 1. Do whatever is the shortest cut for you, like option.get(), anything, so that your code (kind of) works. Step 2. Learn functional programming. Specifically, learn to use Option in a idiomatic, specifically FP-style way. Step 3. Profit. You will benefit a lot from learning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM