我不明白为什么这不起作用...在编译过程中出现以下错误:
[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 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]())
}
最佳答案
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)
关于scala - Scala 案例类的备用构造函数未定义 : not enough arguments for method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016331/