scala - Scala 案例类的备用构造函数未定义 : not enough arguments for method

标签 scala

我不明白为什么这不起作用...在编译过程中出现以下错误:

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

相关文章:

Scala 的 Java 7 风格自动资源管理

scala - Gatling:在几秒钟内了解 rampUsersPerSec(minTPS) 到 maxTPS

scala - 在 Intellij Scala 插件中显示推断类型

scala - 有条件地包含提供的范围依赖与 sbt 和通用插件

Scala Packrat 解析器、错误消息和引用透明性

Scala 类型转换和避免 asInstanceOf

Scala-还有另一种方法来编写这个 foreach 方法吗?

scala - 如何在 SBT 中的 onLoad Hook 上应用设置更改?

java - 如何在 IntelliJ Idea 中查看对象的完整类型名称?

scala - 为什么Scala在类(class)名的末尾加一个美元符号?