scala - 构造函数中常量的用法

标签 scala

这很可能是一个愚蠢的问题,我已经在这里看到了答案,但似乎不适用于我的特定情况。这是我的代码

object ProductAdded{
  val PRODUCT_NAME:String="productName"
  val PRODUCT_PRICE:String="productPrice"
}

class ProductAdded @JsonCreator()(@JsonProperty(PRODUCT_NAME) var productName: String,
                                  @JsonProperty(PRODUCT_PRICE) var productPrice: String) extends Event {


  @JsonProperty(PRODUCT_NAME) def getProductName: String = {
    productName
  }

  @JsonProperty(PRODUCT_PRICE) def getProductPrice: String = {
    productPrice
  }
}

我试图在构造函数中使用这些常量,但是当我编译时显示此错误

Error:(12, 49) annotation argument needs to be a constant; found: event.ProductAdded.PRODUCT_NAME
class ProductAdded @JsonCreator()(@JsonProperty(PRODUCT_NAME) var productName: String,

最佳答案

我必须说,这是一个非常不幸的错误消息,因为 Scala 实际上没有一个名为“常量”的概念,所以如果你甚至不知道它是什么,你应该如何使其成为“常量”是?

Scala 确实,但是,有一个“constant expression”的概念(粗体强调我的):

6.24 Constant Expressions

Constant expressions are expressions that the Scala compiler can evaluate to a constant. The definition of "constant expression" depends on the platform, but they include at least the expressions of the following forms:

  • A literal of a value class, such as an integer
  • A string literal
  • A class constructed with Predef.classOf
  • An element of an enumeration from the underlying platform
  • A literal array, of the form Array(c1, …, cn), where all of the ci's are themselves constant expressions
  • An identifier defined by a constant value definition.

和“constant value definition ”(粗体强调我的):

A constant value definition is of the form

final val x = e

where e is a constant expression. The final modifier must be present and no type annotation may be given.

因此,正如您所看到的,您的表达式不是常量值表达式,因为定义不是常量值定义

为了将其转换为常量值定义,您需要

  • 删除类型注释:String
  • 显式添加 final 修饰符:即使单例对象的成员隐式 final 常量值定义需要显式注释

结果看起来像这样:

object ProductAdded {
  final val PRODUCT_NAME  = "productName"
  final val PRODUCT_PRICE = "productPrice"
}

class ProductAdded @JsonCreator()(
  @JsonProperty(PRODUCT_NAME)  var productName:  String,
  @JsonProperty(PRODUCT_PRICE) var productPrice: String
) extends Event {
  @JsonProperty(PRODUCT_NAME)  def getProductName  = productName
  @JsonProperty(PRODUCT_PRICE) def getProductPrice = productPrice
}

关于scala - 构造函数中常量的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318476/

相关文章:

javascript - 如果您使用 SBT 0.10 或更高版本,如何缩小 Javascript

mongodb - Scala 的 MongoDriver + http4s : How to check if createCollection() throws an exception?

scala - LIFT 设置 Web 项目 : generate with mvn, 并使用 sbt 进行管理

scala - Akka 中的 Futures 和 Agents 比 Clojure 的同类产品有什么优势?

scala - 获取调用类

scala - 使用 SBT 创建新的 Scala 项目?

scala - 从 Spark 数据框中提取列值并将其添加到另一个数据框中

scala - Scala 2.10 中将(或将要)添加哪些新功能到 Scaladoc?

scala - 关于 postfix toString 方法,这两个 Scala 代码段有什么区别?

scala - 如何获取上传文件的路径