Scala:编译时间常数 [英] Scala: Compile time constants

查看:91
本文介绍了Scala:编译时间常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

const int myConst = 5 * 5;

myConst内联为文字25。是:

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

final val myConst = 5 * 5

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

equivalent or is there some other mechanism/ syntax?

推荐答案

是的, final val 是正确的语法,其中 Daniel的告诫。但是,在适当的Scala样式中,您的常数应为驼峰式大写字母。

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.

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

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.

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

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
}

这篇关于Scala:编译时间常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆