Scala案例类中未定义备用构造函数:方法所需参数不足

3

我无法弄清楚为什么这个不起作用...在编译期间,我收到以下错误:

[error] /Users/zbeckman/Projects/Glimpulse/Server-2/project/glimpulse-server/app/service/GPGlimpleService.scala:17: not enough arguments for method apply: (id: Long, glimpleId: Long, layerOrder: Int, created: Long, attachments: List[models.GPAttachment])models.GPLayer in object GPLayer.
[error] Unspecified value parameter attachments.
[error]     private val layer1: List[GPLayer] = List(GPLayer(1, 42, 1, 9), GPLayer(2, 42, 2, 9))

对于这个case class...请注意备用构造函数的定义:

case class GPLayer(id: Long, glimpleId: Long, layerOrder: Int, created: Long, attachments: List[GPAttachment]) {
    def this(id: Long, glimpleId: Long, layerOrder: Int, created: Long) = this(id, glimpleId, layerOrder, created, List[GPAttachment]())
}
2个回答

5
GPLayer(1, 42, 1, 9)

这与编写

是相同的。
GPLayer.apply(1, 42, 1, 9)

因此,您不应该定义另一个构造函数,而是应该在伴生对象 GPLayer 中定义替代的 apply 方法。
case class GPLayer(id: Long, glimpleId: Long, layerOrder: Int, created: Long, attachments: List[GPAttachment]) 

object GPLayer {
  def apply(id: Long, glimpleId: Long, layerOrder: Int, created: Long) = GPLayer(id, glimpleId, layerOrder, created, List[GPAttachment]())
}

如果你想调用替代构造函数,你必须添加 new 关键字:

new GPLayer(1, 42, 1, 9)

编辑:正如Nicolas Cailloux所提到的那样,你的替代构造函数实际上只是为成员attachments提供了一个默认值,因此最好的解决方案是不引入新的方法,而是按照以下方式指定这个默认值:

case class GPLayer(id: Long, glimpleId: Long, layerOrder: Int, created: Long, attachments: List[GPAttachment] = Nil)

哦,我的天啊。谈论盲目地看待自己的代码。谢谢! - Zaphod

2
请注意,在您的情况下,您可以为最后一个参数提供默认值:
case class GPLayer(id: Long, glimpleId: Long, layerOrder: Int, created: Long, attachments: List[GPAttachment] = List())

由于问题中的代码实际上只是指定了一个默认参数,因此这比添加另一个构造函数/apply方法要干净得多。我在我的答案中加入了这个信息(并给了您荣誉),但如果您不喜欢我参与您的回答,我会将其删除;如果是这样,请在我的用户名后添加评论,这样我就会收到通知。无论如何:好的补充 +1 - Kulu Limpa
没问题,因为你的回答得分更高,更容易被看到! - Nicolas Cailloux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接