I'm create a number of json messages for spray in scala using case classes. For example:
case class Foo(name: String, attrs: List[String])
implicit val fooFormat = jsonFormat2(Foo)
object Foo {
case class Invalid(error: String)
}
case class Bar(name: String, kv: Map[String, String])
implicit val barFormat = jsonFormat2(Bar)
In the above snippet, barFormat
compiles, but fooFormat
does not:
type mismatch; found : Foo.type required: (?, ?) => ?
Note: implicit value barFormat is not applicable here because it comes
after the application point and it lacks an explicit result type
I don't want to use barFormat
in place of fooFormat
, and I understand that a case class automatically generates a companion object, but I don't understand why there's a compiler error here, and the error message is difficult for me to decipher. Does anyone know what the problem is here and how to fix it, preferably without removing my Foo
companion object?
When you want to define some functionality related to a case class you have two possible ways to do this. The first one is to create functions directly in the case class. Note that in order to define a companion object for a class you have to set the same names for them and declare them in the same file.
While all of these features are great benefits to functional programming, as they write in the book, Programming in Scala (Odersky, Spoon, and Venners), “the biggest advantage of case classes is that they support pattern matching.” Pattern matching is a major feature of FP languages, and Scala's case classes provide a ...
From your compile error, it looks like jsonFormat2
expects a two-argument function. Do you mean to pass the constructors of Foo
and Bar
into it? If so, you should do Foo.apply
and Bar.apply
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With