将案例类的伴随对象用作类型参数时编译错误

jon*_*rry 4 scala spray

我使用case类创建了一些用于在scala中喷涂的json消息.例如:

  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)
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,barFormat编译但fooFormat不是:

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
Run Code Online (Sandbox Code Playgroud)

我不想barFormat代替使用fooFormat,并且我理解case类自动生成一个伴随对象,但是我不明白为什么这里有编译器错误,并且我很难解释错误消息.有谁知道这里的问题是什么以及如何解决它,最好不要删除我的Foo伴侣对象?

geo*_*liu 8

从您的编译错误,它看起来像jsonFormat2期望一个双参数函数.你的意思是传递的构造FooBar成吗?如果是这样,你应该做的Foo.applyBar.apply.