【问题标题】:Possible to have named constants in scala?可以在scala中命名常量吗?
【发布时间】:2013-09-27 22:13:53
【问题描述】:

看起来注解在 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 无法将静态最终 val 识别为常量值。

这里有什么可做的吗,还是根本不可能在 scala 中命名常量?

【问题讨论】:

    标签: scala


    【解决方案1】:

    这看起来像一个错误。

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

    SLS 4.1 说常量值定义final val x = e 意味着xe 替换。

    它不是那样工作的,所以要么是规范错误,要么是实现错误。

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

    这是this question 的副本,其中retroonym 承诺会为此开张票。

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

    【讨论】:

    • 看起来答案是否定的。
    【解决方案2】:

    您的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 {
    }
    

    【讨论】:

    • 你是说编译器证明提供的类型不是常量,因为它有setter方法?或者它只是使用关于哪些内置类型是不可变的知识?究竟是什么决定了一个常数?
    • 我不完全确定,但 Som-snytt 的回答更详细。
    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    相关资源
    最近更新 更多