Zaphod
Zaphod

Reputation: 1417

Alternate constructor on Scala case class not defined: not enough arguments for method

I can't figure out why this doesn't work... During compile I get the following error:

[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))

For this case class... note the definition of an alternate constructor:

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]())
}

Upvotes: 3

Views: 851

Answers (2)

Kulu Limpa
Kulu Limpa

Reputation: 3541

GPLayer(1, 42, 1, 9)

is the same as writing

GPLayer.apply(1, 42, 1, 9)

So instead of defining an alternative constructor, you should define an alternative apply method in the companion object 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]())
}

If you want to call the altnernative constructor instead, you must add the new-keyword:

new GPLayer(1, 42, 1, 9)

Edit: As Nicolas Cailloux mentioned, your alternative constructor is really just providing a default value for the member attachments, so the best solution would actually be to not introduce a new method, but to specify this default value as follows:

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

Upvotes: 5

Nicolas Cailloux
Nicolas Cailloux

Reputation: 448

Note that in your case, you could just provide a default value for the last argument :

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

Upvotes: 2

Related Questions