6

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!

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
user1253952
  • 1,577
  • 8
  • 22
  • 34
  • http://stackoverflow.com/questions/11198998/scala-play-2-passing-request-to-method also see comments below Travis Brown's answer. – user1253952 Jul 22 '12 at 06:15

2 Answers2

8

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.

xadhix
  • 174
  • 15
Travis Brown
  • 138,631
  • 12
  • 375
  • 680
  • Thanks much! noted that I should handle the null/Option case as well. Perhaps I'm having a more basic issue. I'm getting the error "not found: value request". – user1253952 Jul 20 '12 at 19:31
  • Where are you trying to use it? – Travis Brown Jul 20 '12 at 19:33
  • In one of my controller files, in a very basic method: def getName = request.get("myHeader") – user1253952 Jul 20 '12 at 19:36
  • Using this class (http://www.playframework.org/documentation/api/2.0/java/play/mvc/Http.Request.html). If I try to do: println(play.mvc.Http.Request.getHeader("MyHeader")), it will error with the message: "value getHeader is not a member of object play.mvc.Http.Request". Is there a reason I can't use this java object? – user1253952 Jul 20 '12 at 19:49
  • That `getHeader` method isn't static. You probably want to do something like [this](http://stackoverflow.com/q/11198998/334519). – Travis Brown Jul 20 '12 at 20:05
  • Should this be `request.headers` instead of just `request`? – Michael Mior May 30 '22 at 13:42
5

Accepted answer doesn't work for scala with playframework 2.2:

request.get("myHeader").getOrElse("")

It gives me the below error:

value get is not a member of play.api.mvc.Request[play.api.mvc.AnyContent]

use below

request.headers.get("myHeader").getOrElse("") 
Govind Singh
  • 15,282
  • 14
  • 72
  • 106