3

I'm trying to wrap the spray-json parser such that it returns an Option rather than throws an exception.

As a first step I'm just trying to wrap the method with my own, but I'm having problems making it generic.

The parser uses an implicit format object (which is defined for the concrete type I'm using) but when the method is generic the compiler complains:

[error]     Cannot find JsonReader or JsonFormat type class for T
[error]     def parse[T](s: String): T = JsonParser(s).convertTo[T]

Here's the relevant code:

case class Person(name: String)

object Protocols {
  implicit val personFormat = jsonFormat1(Person)
}

import spray.json._

object Parser {
  import com.rsslldnphy.json.Protocols._
  // JsonParser(s).convertTo[Person] works fine, but..
  def parse[T](s: String): T = JsonParser(s).convertTo[T]  // .. doesn't
}  

What do I need to do to get this to work?

Russell
  • 11,742
  • 3
  • 47
  • 72

1 Answers1

5

You need to pass the required implicit value, which can conveniently be done using the "context bound" shortcut notation:

def parse[T : JsonReader](s: String): T =
  JsonParser(s).convertTo[T]

This is equivalent to:

def parse[T](s: String)(implicit reader: JsonReader[T]): T =
  JsonParser(s).convertTo[T]

See What is a "context bound" in Scala?

Community
  • 1
  • 1
Régis Jean-Gilles
  • 31,374
  • 4
  • 75
  • 92
  • Ace, thanks for that! Not sure I'm a fan of the shortcut notation so I think I'll stick with the "more explicit implicit", so to speak. – Russell Nov 10 '12 at 21:49
  • 1
    I would suggest you to get used to this notation, as it is prevalent in idiomatic scala code. And actually this notation makes a lot of sense as soon as you think of `JsonReader` as a type class. See http://stackoverflow.com/questions/5408861/what-are-type-classes-in-scala-useful-for – Régis Jean-Gilles Nov 10 '12 at 22:07
  • I don't necessarily want to write idiomatic Scala code. In my opinion Scala falls on the side of brevity over clarity a few too many times, and this is one of them. – Russell Nov 10 '12 at 23:46