这很可能是一个愚蠢的问题,我已经在这里看到了答案,但似乎不适用于我的特定情况。这是我的代码
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. Thefinal
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/