PS

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 the cI'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.

finalfinal 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にさえならないようである。

参考文献

*1:サポートされる見込みはないらしい