Constant expressions
Constant expressions
SLS 6.24より、constant expressionとは(基本的に)以下のいずれかである:
- 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 thecI
's are themselves constant expressions - An identifier defined by a constant value definition.
Constant value definition
SLS 4.1より:
- A constant value definition is of the form
final val x = e
where e is a constant expression.
final
はfinal class
内のval
でも必須である(SLS 5.2)。なぜかfinal val x: T = e
だと駄目らしい。
vs. Macro
reflect/api/Constants.scala
より、Literal(Constant(_))
で受け取れる(と思われる)のは:
- Literals of primitive value classes (bytes, shorts, ints, longs, floats, doubles, chars, booleans and voids).
- String literals.
- References to classes (typically constructed with
Predef.classOf
). - References to enumeration values.
Literal arrayは含まれていない。*1
Unit
なぜか
final val u = ()
は、Literal(Constant(_))
で受け取れない。()
はliteralではないからconstant expressionではない、ということだろうか。
String interpolation
String interpolationをつかうと、(今のところ)string literalにさえならないようである。
参考文献
- SLS.pdf
- [SI-3183] Constant Expressions not allowed as ClassfileAnnotation annotation arguments: Array(""); constant value definition containing class, or Array - Scala
- java - How do I specify a static array in a Scala 2.8 annotation? - Stack Overflow
*1:サポートされる見込みはないらしい