Search code examples
scalafor-comprehension

scala: how to rewrite this function using for comprehension


I have this piece of code with a couple of nasty nested checks...

I'm pretty sure it can be rewritten with a nice for comprehension, but I'm a bit confused about how to mix the pattern matching stuff

// first tries to find the token in a header: "authorization: ideas_token=xxxxx"
// then tries to find the token in the querystring: "ideas_token=xxxxx"
private def applicationTokenFromRequest(request: Request[AnyContent]): Option[String] = {

  val fromHeaders: Option[String] = request.headers.get("authorization")
  val tokenRegExp = """^\s*ideas_token\s*=\s*(\w+)\s*$""".r

  val tokenFromHeader: Option[String] = {
    if (fromHeaders.isDefined) {
      val header = fromHeaders.get
      if (tokenRegExp.pattern.matcher(header).matches) {
        val tokenRegExp(extracted) = header
        Some(extracted)
      } else {
        None
      }
    } else {
      None
    }
  }

  // try to find it in the queryString
  tokenFromHeader.orElse {
    request.queryString.get("ideas_token")
  }

}

any hint you can give me?


Solution

  • You can get rid of a lot of the cruft by just using the extractor in a for-comprehension:

    val Token = """^\s*ideas_token\s*=\s*(\w+)\s*$""".r
    
    val tokenFromHeader = for {
      Token(t) <- request.headers.get("authorization")
    } yield t
    
    tokenFromHeader orElse request.queryString.get("ideas_token")
    

    But the following is even more concise, and a little clearer, to my eye:

    val Token = """^\s*ideas_token\s*=\s*(\w+)\s*$""".r
    
    request.headers.get("authorization") collect {
      case Token(t) => t
    } orElse request.queryString.get("ideas_token")
    

    The two are essentially equivalent, though—in both cases you're just pulling the value (if it exists) out of the Option and seeing if it matches the regular expression.