如何在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)
等价还是有其他机制/语法?
是的,这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)
final val是这样做的方式.如果可以的话,编译器将使它成为编译时常量.
请阅读下面的丹尼尔评论,了解"如果可以"的含义.
| 归档时间: |
|
| 查看次数: |
1251 次 |
| 最近记录: |