You don't need to specify a return type in scala. In this case the return type is inferred as Option[Long].
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 valueIt's okay, since cookies is a Map[String, String] so running the get returns an Option[String].
If 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
}function return types are not required in scala, although every style guide I've seen requires them for any non-trivial function
I only use them on methods/vals that are intended to be publicly used just so I don't inadvertently change the type of something and break someone else's code. Within private methods, it doesn't really matter.
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).