Description
String interpolations are great, but they could be even greater by taking inspiration from collection literals.
We currently allow any expression inside an interpolation block (${...}
). If we instead treated interpolations like elements of a collection of String
s, then we could allow for
, if
and spread elements too.
Example (one with everything):
bool sep = false;
var jsonText = """
{
${for (var key in map.keys)
if (!key.startsWith('_'))
...[if (sep == (sep = true) ",\n",
' ', key, ":", map[key]]}
}
""";
One use-case I often run into is optionally adding some text to the string:
"example${name != null ? "($name)" : ""}: something"
Here the : ""
is annoying and superfluous. With if
-interpolation we can write it as:
"example${if (name != null) "($name)"}: something"
May even want to allow a comma-separated sequence of interpolation elements inside an interpolation:
"example${if (name != null) "($name)", if (age != null) "age: $age"}"
Not technically necessary, one can always just start a new interpolation, but ,
can be shorter than }${
.
May have to consider how well it reads. (And whether it means that we allow zero or more elements, so ${}
would be valid. I have no problem with that, when one can write ${if (false) 0}
or ${?null}
anyway.)
Today you can use list+join.
That has the advantage of also being able to add a separator.
var jsonText = """
{
${[for (var key in map.keys)
if (!key.startsWith('_'))
" $key: ${map[key]}"].join(",\n")}
}
""";
There is no similar concept of a join with separator in elements.