scala: how to rewrite this function using for comprehension
Posted
by
opensas
on Stack Overflow
See other posts from Stack Overflow
or by opensas
Published on 2012-10-30T16:16:18Z
Indexed on
2012/10/30
17:01 UTC
Read the original article
Hit count: 144
scala
|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?
© Stack Overflow or respective owner