Reputation: 2173
My attempt so far ran into java.lang.ClassCastException: scala.runtime.BoxedUnit cannot be cast to scala.Option
. In fact I even can not think how the appropriate response may look like. Is it possible?
Upvotes: 1
Views: 3444
Reputation: 141
To anyone still getting issues returning a future in the complete block, make sure to have an execution context such as scala.concurrent.ExecutionContext.Implicits.global
in scope! IDE tends to not understand this is the problem and can send you down a long rabbit hole.
Upvotes: 0
Reputation: 21557
Here could be two options: either it's a bug in your program or you didn't provide spray any way to marshall your Foo
type, cause Future
and Option
are handled by default. E.g this route can be handled by standard spray marshallers without any problems:
val route = {
(get & path("test")) {
complete {
Future(Option("Hello Spray!"))
}
}
}
Now if you make a GET request on /test you'll get a correct response.
If you have a specific type, then you need to provide you own marshaller of type ToResponseMarshallable
to sray through implicit context. I think the most common and easiest way would be to make a Json response, for this you need a spray-json (or some other supported json lib) and just provide a converter to json, like:
import spray.json.DefaultJsonProtocol._
case class Boy(name: String, age: String)
object Boy {
implicit val boyJson = jsonFormat2(Boy.apply)
}
Now the only thing left to do is place a json marshaller into the scope:
import spray.httpx.SprayJsonSupport._ // import json marshaller
val route = {
(get & path("test") {
complete {
Future(Option(Boy("Name", 0)))
}
}
}
Now you'll get a json response. IF you need some other kind of response, make a custom marshaller for a Boy type.
Upvotes: 6
Reputation: 16412
In short - Yes, but you need to make compiler happy.
Spray lets you return Future
or plain response as long as it can be marshalled back to a response. You need to make sure that you either have implicit conversions in the scope that do the marshalling for you or transform your Foo
object explicitly.
Here is how response transformation is performed: http://spray.io/documentation/1.2.0/spray-httpx/response-transformation/.
Upvotes: 1