Scala:编译时间常数

Ric*_*ver 5 scala constants

如何在Scala中声明编译时常量?在C#中,如果你声明

const int myConst = 5 * 5;
Run Code Online (Sandbox Code Playgroud)

myConst以字面值25表示.是:

final val myConst = 5 * 5
Run Code Online (Sandbox Code Playgroud)

等价还是有其他机制/语法?

lee*_*777 8

是的,这final val是正确的语法,丹尼尔的警告.但是,在适当的Scala风格中,你的常量应该是带有大写首字母的camelCase.

如果您希望在模式匹配中使用常量,则以大写字母开头很重要.第一个字母是Scala编译器如何区分常量模式和变量模式.请参见Scala中Programming 15.2 .

如果a val或singleton对象不以大写字母开头,要将其用作匹配模式,则必须将其括在反引号中(``)

x match {
  case Something => // tries to match against a value named Something
  case `other` =>   // tries to match against a value named other
  case other =>     // binds match value to a variable named other
}
Run Code Online (Sandbox Code Playgroud)


Rex*_*err 5

final val是这样做的方式.如果可以的话,编译器将使它成为编译时常量.

请阅读下面的丹尼尔评论,了解"如果可以"的含义.

  • 您忘记了两个要点:它必须在编译时静态解析 - 我不确定Scala在编译时是否进行文字算术 - 而且,很容易出错,_it必须没有type_.如果你声明它为`final val myConst:Int = 5`,它将不会被视为常量. (14认同)