The scala example is plain wrong.
import play.api.mvc.RequestHeader
def getUserId()(implicit request: RequestHeader) = { request.cookies.get("uid").map(_.value.toLong).filter(_ > 0) }
Return type is missing, it will throw exception (toLong).
import play.api.mvc.RequestHeader
def getUserId()(implicit request: RequestHeader) = { request.cookies.get("uid").map(_.value.toLong).filter(_ > 0) }
Return type is missing, it will throw exception (toLong).
You are correct about the exception if the cookie's value can't be parsed as a Long. You might instead write the code as:
def getUserId()(implicit request: RequestHeader): Option[Long] = {
request.cookies.get("uid")
.flatMap(cookie => Try(cookie.value.toLong).toOption)
.filter(_ > 0)
}
or, equivalently: def getUserId()(implicit request: RequestHeader): Option[Long] = for {
cookie <- request.cookies.get("uid")
value <- Try(cookie.value.toLong).toOption if value > 0
} yield valueIf the author is concerned, the way to express this to be more expressive could be something like this:
val uidOpt: Option[Long] = request.cookies.get("uid") map {
case Some(uidStr) if uidStr.toLong > 0 => Some(uidStr.toLong)
case _ => None
}