Scala: Compile time constants

我的梦境 提交于 2019-12-17 20:48:21

问题


How do you declare compile time constants in Scala? In C# if you declare

const int myConst = 5 * 5;

myConst is in-lined as the literal 25. Is:

final val myConst = 5 * 5

equivalent or is there some other mechanism/ syntax?


回答1:


Yes, final val is the proper syntax, with Daniel's caveats. However, in proper Scala style your constants should be camelCase with a capital first letter.

Beginning with a capital letter is important if you wish to use your constants in pattern matching. The first letter is how the Scala compiler distinguishes between constant patterns and variable patterns. See Section 15.2 of Programming in Scala.

If a val or singleton object does not begin with an uppercase letter, to use it as a match pattern you must enclose it in backticks(``)

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
}



回答2:


final val is the way to do it. The compiler will then make that a compile-time constant if it can.

Read Daniel's comment below for details on what "if it can" means.



来源:https://stackoverflow.com/questions/11195171/scala-compile-time-constants

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!