Have you written code like s"myVal = $myVal"
a thousand times ?
Do you wish it would be simpler ?
Then I have the solution for you:
s"$myVal="
As simple as that !
Inspired by Python’s "=
for self-documenting expressions and debugging"
With more details here
Details:
The pattern for interpolators becomes:
I0: $<name>[=]
or
I1: $[=]<name>
And
I2: ${<expr>}[=]
or
I3: ${<expr>[=]}
(what python uses)
or
I4: $[=]{<expr>}
I recommend what’s in bold
In the case the =
is present, the pattern is converted to the following substring: <name/expr> = ${<name/expr>}
An f-formatter after is considered as part of the normal string, this allows:
${list.head=}%2.2f
-> list.head = ${list.head}%2.2f
-> list.head = 1.90
Upsides:
Faster debugging/experimenting
Less boilerplate
Downsides:
Can be surprising to uninitiated
Can break some code
(depending on I_n chosen, as =
after ${}
is of course allowed, and =
is a valid symbol for methods)
Questions:
Q0 Do you wish there was something like this in the language
Q0.yes Is this a sufficiently good solution?
Q1 Should this only be for s and f strings ?
Q1.no Should we extend StringContext
to pass some information about this pattern (I would say no)
Q2 Should the =
be before or after the name/expr ?
Q2.before.1 Should I1 be allowed ?
Q2.before.2 Should I4 be allowed ?
Q2.after.1 Should I0 be allowed ? (Very useful, but relatively high chance to intersect with usage)
Q2.after.2 Should I2 or I3 be chosen ?
I2: looks more natural, but is way more likely to appear in already existing code
I3: less likely to have appeared, uniform with Python
Potential extensions
Allow spaces around the =
, those will determine the spacing around the =
in the generated string, the way python does it:
s"${a=}" -> s"a=${a}"
s"${a= }" -> s"a= ${a}"
s"${a =}" -> s"a =${a}"
s"${a = }" -> s"a = ${a}"
Update linters to discourage in production code
(In case we discourage it in production code)
Conclusion
I believe this is a very useful quality of life feature, and I’m surprised I’ve not seen anyone put the idea forward before
Thank you for the read, and let me know what you think