valastring-interpolationgenie

How does string interpolation / string templates work?


@lf_araujo asked in this question:

var dic = new dict of string, string
dic["z"] = "23"
dic["abc"] = "42"
dic["pi"] = "3.141"
for k in sorted_string_collection (dic.keys)
    print (@"$k: $(dic[k])")

What is the function of @ in print(@ ... ) and lines_add(@ ...)?

As this is applicable to both Genie and Vala, I thought it would be better suited as a stand-alone question.

The conceptual question is:

How does string interpolation work in Vala and Genie?


Solution

  • There are two options for string interpolation in Vala and Genie:

    1. printf-style functions:

      var name = "Jens Mühlenhoff";
      var s = string.printf ("My name is %s, 2 + 2 is %d", name, 2 + 2);
      

      This works using varargs, you have to pass multiple arguments with the correct types to the varargs function (in this case string.printf).

    2. string templates:

      var name = "Jens Mühlenhoff";
      var s = @"My name is $name, 2 + 2 is $(2 + 2)";
      

      This works using "compiler magic".

      A template string starts with @" (rather then " which starts a normal string).

      Expressions in the template string start with $ and are enclosed with (). The brackets are unneccesary when the expression doesn't contain white space like $name in the above example.

      Expressions are evaluated before they are put into the string that results from the string template. For expressions that aren't of type string the compiler tries to call .to_string (), so you don't have to explicitly call it. In the $(2 + 2) example the expression 2 + 2 is evaluated to 4 and then 4.to_string () is called with will result in "4" which can then be put into the string template.

    PS: I'm using Vala syntax here, just remove the ;s to convert to Genie.