I’m learning Scala, and attempting to understand how traits are working (specifically with the Dispatch library).
I’ve got something like this:
import dispatch._
import dispatch.liftjson._
object Foo
{
def main(cmd: Array[String])
{
val http = new Http;
val req = :/("example.com") / path ># (list ! obj);
val res = http(req);
}
}
Unfortunately, it’s complaining that ># is not registered with dispatch.Request. The trait is described within dispatch.liftjson, and it was my assumption that I should just need to import that trait (which _ should cover) for it to register.
You should be importing from
dispatch.liftjson.Js._.Having a trait isn’t helpful, as you’re not then using it. The
JS._import will bring all the contents of theJSobject into your scope, including the implicit conversionrequestToJsonVerbswhich it has fromtrait ImplicitJsonVerbs. This method converts a standard DispatchRequest, which you have from:/("example.com") / path, to aJsonVerbs, which has the method>#.Here’s an abridged sample of how I query an API:
As you can see, I have the correct imports (plus some for some Lift libraries I like), and my
Requestthen ‘has’ a>#method. I give>#a function that matches the expected signature ((JValue) ⇒ T) and away we go.In case you’re wondering, I’m specifically using lift-json’s ability to extract to case classes, meaning that
Twill beDevice. However, lift-json also throws an exception if it is unable to convert theJValueto aDevice, so I’ve wrapped my whole request withHelper.tryo, a Lift helper method that wraps a try-catch call, returning aBox.Boxis like the standard ScalaOptionbut with the addition ofFailure, which indicates why aBoxis empty. So, in this case I will get either aFull[Device]or aFailure. Handy!