Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala:编译时常量_Scala_Constants_Compile Time Constant - Fatal编程技术网

Scala:编译时常量

Scala:编译时常量,scala,constants,compile-time-constant,Scala,Constants,Compile Time Constant,如何在Scala中声明编译时常量?在C#中,如果您声明 const int myConst = 5 * 5; myConst作为文本25在行中。是: final val myConst = 5 * 5 等效或是否存在其他机制/语法 final val就是这样做的。如果可以的话,编译器将使其成为编译时常量 阅读下面Daniel的评论,了解“如果可以”的详细含义。是的,final val是正确的语法,带有。但是,在适当的Scala样式中,常量应该是大写字母的大小写 如果您希望在模式匹配中使用常量

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

const int myConst = 5 * 5;
myConst作为文本25在行中。是:

final val myConst = 5 * 5

等效或是否存在其他机制/语法

final val
就是这样做的。如果可以的话,编译器将使其成为编译时常量


阅读下面Daniel的评论,了解“如果可以”的详细含义。

是的,
final val
是正确的语法,带有。但是,在适当的Scala样式中,常量应该是大写字母的大小写

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

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


您忘记了两个要点:它必须在编译时进行静态解析——我不确定Scala在编译时是否执行文本算术——而且,很容易出错,它必须没有类型。如果您声明它
final val myConst:Int=5
,它将不会被视为常量。您有关于它的引用吗?它不能有类型?“
final
修饰符必须存在,并且不能给出类型注释。”
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
}