Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to have named constants in scala?

Tags:

scala

It looks like annotations require constants in Java. I'd like to do:

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

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

where

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

is fine.

Sadly, scala doesn't recognize a static final val as a constant value.

Is there's anything to do here, or is it simply not possible to have named constants in scala?

like image 301
user48956 Avatar asked Sep 27 '13 22:09

user48956


2 Answers

This looks like a bug.

SLS 6.24 says a literal array Array(c1, c2, ...) is a constant expression.

SLS 4.1 says a constant value definition final val x = e means x is replaced by e.

It doesn't work that way, so either it's a spec bug or an implementation bug.

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

This is a duplicate of this question where retronym promised to open a ticket about it.

That was three years ago. I wonder if there's still a yellow post-it on his terminal?

like image 150
som-snytt Avatar answered Sep 20 '22 05:09

som-snytt


Your componentstoScan is not a constant in the sense that I can change the contained value:

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

This will work

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

@PropertySource(Array(ConfigStatics.componentsToScan))
class MyConfig extends WebMvcConfigurerAdapter {
}
like image 27
sksamuel Avatar answered Sep 20 '22 05:09

sksamuel