可以在scala中命名常量?

时间:2013-09-27 22:13:54

标签: scala

看起来注释需要Java中的常量。我想这样做:

object ConfigStatics {
  final val componentsToScan = Array("com.example")
}

@PropertySource( ConfigStatics.componentsToScan )   // error: constant value required
class MyConfig extends WebMvcConfigurerAdapter {
}

,其中

@PropertySource( Array("com.example") ) 
class MyConfig extends WebMvcConfigurerAdapter {
}

很好。

可悲的是,scala不会将静态最终值视为常量值。

这里有什么可做的,或者它是不可能在scala中使用命名常量?

2 个答案:

答案 0 :(得分:4)

在我可以更改包含值的意义上,componentstoScan不是常数:

object ConfigStatics {
  final val componentsToScan = Array("com.example")
  componentsToScan(0) = "com.sksamuel"
}

这将有效

object ConfigStatics {
  final val componentsToScan = "com.example"
}

@PropertySource(Array(ConfigStatics.componentsToScan))
class MyConfig extends WebMvcConfigurerAdapter {
}

答案 1 :(得分:4)

这看起来像个错误。

SLS 6.24表示文字数组Array(c1, c2, ...)是一个常量表达式。

SLS 4.1表示常量值定义final val x = e表示x替换为e

它不起作用,所以要么是规范错误,要么是实现错误。

  final val j = Array(1,2,3)
  def k = j  // j
  final val x = 3
  def y = x  // 3

这是this question的副本,其中反义词承诺打开一张关于它的票据。

那是三年前的事。我想知道他的终端上是否还有一个黄色的帖子?

相关问题