Search code examples
constantsrakustring-interpolation

Why aren't variables interpolated in `constant` declarations?


use v6.d;

my Str $foo = 'Hello';
my constant $BAR = "--$foo--";
say $BAR;

OUTPUT:

Use of uninitialized value element of type Str in string context.
Methods .^name, .raku, .gist, or .say can be used to stringify it to something meaningful.
  in block  at deleteme.raku line 4
----

Expected OUTPUT:

--Hello--

The same thing happens without the my or with our in place of my.

[187] > $*DISTRO
macos (12.6)
[188] > $*KERNEL
darwin
[189] > $*RAKU
Raku (6.d)


Solution

  • The value assigned to a constant is evaluated at compile time, not runtime. This means that constant values can be calculated as part of the compilation and cached.

    Regular assignments happen at runtime. Thus, in:

    my Str $foo = 'Hello';
    my constant $BAR = "--$foo--";
    

    The assignment to $foo has not taken place at the time "--$foo--" is evaluated. By contrast, if $foo were to be a constant, the value is available at compile time and interpolated, so:

    my constant $foo = 'Hello';
    my constant $BAR = "--$foo--";
    say $BAR;
    

    Produces:

    --Hello--