4 ms·
The scala example is plain wrong. import play.api.mvc.RequestHeader def getUserId()(implicit request: RequestHeader) = { request.cookies.get("uid").map(_.va
by etaty 10y ago
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).
- sedro 10y agoYou 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 value
- jcdavis 10y agofunction return types are not required in scala, although every style guide I've seen requires them for any non-trivial function
- mi100hael 10y agoI 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.
- mark242 10y agoIt'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 }
- dcu 10y agoit's funny, this discussion alone kind of proves the author's point