user48956
user48956

Reputation: 15788

Possible to have named constants in 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?

Upvotes: 6

Views: 342

Answers (2)

som-snytt
som-snytt

Reputation: 39577

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?

Upvotes: 4

sksamuel
sksamuel

Reputation: 16387

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

Upvotes: 4

Related Questions