Section 2.2

Showing a value

Interpolation — sliding an expression into a text, with nothing assembled by hand.

The previous sub-section put a sentence together with +, and found it heavy going. Here is the lighter spelling it promised — and it settles, along the way, a question we had not yet asked: Console.print accepts nothing but a text, so how do you show a number?

By sliding the value into the text, at the place where it should appear.

@entry(start)
object MyProgram {
    start() {
        var name := "Simon Magus";
        var age := 42;
        var height := 1.83;
        var registered := true;

        Console.print(text: $"{name}, {age} years old, {height} m");
        Console.print(text: $"registered: {registered}");
        Console.print(text: $"in ten years: {age + 10} years old");
    }
}

Three lines of output, and not one conversion written by hand.

$"…" — a text with holes

A text prefixed with $ is no longer an ordinary text: what it carries between braces is an expression, evaluated and inserted in its place.

$"{name}, {age} years old, {height} m"

Three holes, three values, and three different types — a text, an integer, a float. You had nothing to convert: the compiler does it, and it knows what type each hole is because it already knows the type of each variable.

The $ sign was chosen because it was free. It was used nowhere else in the language — the compiler refused it outright as an invalid character. There was therefore no ambiguity to settle in giving it this role, unlike Python’s f"…" form, where f is a valid name like any other.

Any expression, not just a name

A hole is not limited to a variable. Anything that produces a value fits:

$"in ten years: {age + 10} years old"

The computation happens where its result is read — not three lines above, in a variable that exists for nothing else.

What this replaces

Take the + from the previous sub-section and try to slide a number into it: it is no longer enough. Gluing two texts worked; gluing a text and an integer first requires converting the integer into a text.

Console.print(text: name + ", " + age.toText() + " years old");

That spelling exists, and you will meet it — but .toText() is not offered by default: it has to be asked for, which shows at the top of the file. We will come to it when the need arises.

Interpolation spares you both chores at once: nothing to glue, nothing to convert, and the sentence reads in the order it will come out.

Your turn

  • Add a line showing the height in centimetres: {height * 100}.
  • Put a whole text inside a hole: $"{"hello"}". It works, and it is of no use whatsoever — but it does say that a hole takes an expression, not a variable name.
  • Remove the $ in front of one of the texts and run: the braces become braces again, and are printed as they are.