Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala play 2.0 get request header

I am converting some of my java code to scala and I would like to be able to get a specific header and return it as a string.

In java I have:

return request().getHeader("myHeader")

I have been unable to achieve the same thing in scala. Any help would be greatly appreciated! Thanks!

like image 720
user1253952 Avatar asked Jul 20 '12 18:07

user1253952


1 Answers

You could write:

request.get("myHeader").orNull

If you wanted something essentially the same as your Java line. But you don't!

request.get("myHeader") returns an Option[String], which is Scala's way of encouraging you to write code that won't throw null pointer exceptions.

You can process the Option in various ways. For example, if you wanted to supply a default value:

val h: String = request.get("myHeader").getOrElse("")

Or if you want to do something with the header if it exists:

request.foreach { h: String => doSomething(h) }

Or just:

request foreach doSomething

See this cheat sheet for more possibilities.

like image 92
Travis Brown Avatar answered Sep 20 '22 04:09

Travis Brown