我无法弄清楚为什么这不起作用...在编译期间我收到以下错误:
[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))
Run Code Online (Sandbox Code Playgroud)
对于这个案例类...请注意备用构造函数的定义:
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]())
}
Run Code Online (Sandbox Code Playgroud)
GPLayer(1, 42, 1, 9)
Run Code Online (Sandbox Code Playgroud)
和写作一样
GPLayer.apply(1, 42, 1, 9)
Run Code Online (Sandbox Code Playgroud)
因此,您应该apply在随播对象中定义替代方法,而不是定义替代构造函数GPLayer.
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]())
}
Run Code Online (Sandbox Code Playgroud)
如果要改为调用altnernative构造函数,则必须添加new-keyword:
new GPLayer(1, 42, 1, 9)
Run Code Online (Sandbox Code Playgroud)
编辑:正如Nicolas Cailloux所提到的,您的替代构造函数实际上只是为成员提供默认值attachments,因此最佳解决方案实际上是不引入新方法,而是指定此默认值,如下所示:
case class GPLayer(id: Long, glimpleId: Long, layerOrder: Int, created: Long, attachments: List[GPAttachment] = Nil)
Run Code Online (Sandbox Code Playgroud)