String Interpolation

Arafel er.krali at gmail.com
Thu Oct 26 09:42:27 UTC 2023


On 26/10/23 3:47, Adam D Ruppe wrote:
> On Thursday, 26 October 2023 at 00:24:33 UTC, Walter Bright wrote:
>> The money shot:
>>
>> "The design of template expressions deliberately makes it impossible 
>> to go directly from a string literal or text block with embedded 
>> expressions to a String with the expressions' values interpolated. 
>> This prevents dangerously incorrect strings from spreading through a 
>> program."
> 
> Yup. Even if we went with an object in D instead of a tuple, I'd be 
> against the `alias toString this;` part. Just too much history saying 
> that's a bad idea for D to embrace it at this point.

You are not mentioning this part:

> The template expression STR."..." is a shortcut for invoking the process method of the STR template processor. That is, the now-familiar example:
> 
> String name = "Joan";
> String info = STR."My name is \{name}";
> 
> is equivalent to:
> 
> String name = "Joan";
> StringTemplate st = RAW."My name is \{name}";
> String info = STR.process(st);
> 
> where RAW is a standard template processor that produces an unprocessed StringTemplate object.

I would find it perfect if there were an option to define arbitrary 
prefixes to strings (other than the ones already used by the language), 
like `i"Hello, ${name}` or `sql"SELECT * FROM ${table};"`. Notice how 
the string itself doesn't need any marker in Java:

> String name = "Joan";
> String info = "My name is \{name}";
> | error: processor missing from template expression

It's needing both what I don't like and find confusing: `string s = 
i"Hello, ${world}".format` (or `.text`).

We can do like Java, and assume that as soon as a template expression is 
found, it will be automatically considered an interpolated string, so 
actually strings literals will be interpolated by default, and only if 
there are no expressions the result would be a `string`.


More information about the Digitalmars-d mailing list