Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error when using a companion object of a case class as a type parameter

Tags:

scala

spray

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?

like image 279
jonderry Avatar asked Jun 17 '14 21:06

jonderry


People also ask

Can case class have 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.

What is the benefit of case class in Scala?

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 ...


Video Answer


1 Answers

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.

like image 166
geoffliu Avatar answered Sep 18 '22 14:09

geoffliu