12

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

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

class Example
{
    public readonly static Double GoldenRatio;

    static Example ()
    {
        GoldenRatio = (1.0 + Math.Sqrt (5.0)) / 2.0;
    }
}
sungiant
  • 3,152
  • 5
  • 32
  • 49
  • It's considered bad practice to have public variables. Consider using Properties instead. `public static double GoldenRatio {get; private set;}` should do the trick – Electric Coffee Jul 18 '14 at 14:28

1 Answers1

29

It would be just a val member:

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

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

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • 1
    When, exactly, will the expression get evaluated? – sungiant Jul 18 '14 at 14:18
  • 2
    @Pooky the expression is evaluated immediately. If you want it to be evaluated when it's first called use `lazy val` if you want it to be evaluated every time it's called use `def` – Electric Coffee Jul 18 '14 at 14:27
  • 2
    @Pooky if you're looking for compile-time evaluation, you can make it "final val". See http://stackoverflow.com/a/11197537/303940. In the case of the GoldenRatio, however, which requires some math to be performed, you may need to use a Macro to evaluate during compile time and turn it into a literal. – KChaloux Jul 18 '14 at 14:32
  • @ElectricCoffee: No it is not evaluated immediately, but the first time when the defining object is called. – kiritsuku Jul 18 '14 at 17:17
  • @sschaef I would've assumed the object, being a singleton is evaluated at declaration – Electric Coffee Jul 18 '14 at 17:36
  • @ElectricCoffee The class file containing the object needs to be loaded, and its initialization is only run then. – Alexey Romanov Jul 18 '14 at 20:26