类的伴随对象作为类型参数时编译错误

类的伴随对象作为类型参数时编译错误

本文介绍了使用 case 类的伴随对象作为类型参数时编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用案例类在 Scala 中创建许多用于喷射的 json 消息.例如:

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)

在上面的代码段中,barFormat 编译,但 fooFormat 没有:

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

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

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?

推荐答案

从您的编译错误来看,看起来 jsonFormat2 需要一个双参数函数.你的意思是将 FooBar 的构造函数传入其中吗?如果是这样,您应该执行 Foo.applyBar.apply.

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.

这篇关于使用 case 类的伴随对象作为类型参数时编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 20:01