Scala: how to rewrite this function, using for understanding

I have this piece of code with some nasty nested checks ...

I'm sure it can be rewritten with a good understanding, but I'm a little confused about how to mix material that matches the pattern

// 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?

+4
source share
1 answer

You can get rid of a lot of cracks just by using the extractor in the for feeling:

 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 slightly clear, in my opinion:

 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") 

Both are essentially equivalent, although in both cases you simply pull the value (if it exists) from Option and see if it matches the regular expression.

+7
source

Source: https://habr.com/ru/post/1443039/


All Articles