如何在 Scala 中定义常量成员?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24826800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:25:02  来源:igfitidea点击:

How to define a constant members in Scala?

scala

提问by sungiant

What is the correct was to define a constant such as Pi or the Golden Ratio in a Scala program?

在 Scala 程序中定义常量(例如 Pi 或黄金比例)的正确做法是什么?

As an example, in C# I can do this:

例如,在 C# 中,我可以这样做:

class Example
{
    public readonly static Double GoldenRatio;

    static Example ()
    {
        GoldenRatio = (1.0 + Math.Sqrt (5.0)) / 2.0;
    }
}

回答by Ionu? G. Stan

It would be just a valmember:

它只是一个val成员:

object Example {
  val GoldenRatio = (1.0 + Math.sqrt(5.0)) / 2.0
}

Also, take a look at the Scala Style Guide section regarding constants.

另外,请查看有关常量Scala 样式指南部分