TemplatedString.builder() produces mutable TemplateString?

Jim Laskey james.laskey at oracle.com
Wed Sep 21 12:03:08 UTC 2022


Pushed change:


/**
 * Returns a {@link TemplatedString} based on the current state of the
 * {@link TemplateBuilder Builder's} fragments and values.
 *
 * @return a new TemplatedString
 */
public TemplatedString build() {
    return TemplatedString.of(fragments, values);
}






On Sep 20, 2022, at 11:13 PM, Jim Laskey <james.laskey at oracle.com<mailto:james.laskey at oracle.com>> wrote:

Thank you for reporting. I’ll check into this.

Cheers,

— Jim


📱

On Sep 20, 2022, at 10:58 PM, Nathan Walker <nathan.h.walker at gmail.com<mailto:nathan.h.walker at gmail.com>> wrote:


Hey folks,

I was poking around at the source in the templated-string branch and saw something that seemed odd.

In the TemplatedString.TemplateBuilder.build() method there is:

/**
 * Returns a {@link TemplatedString} based on the current state of the
 * {@link TemplateBuilder Builder's} fragments and values.
 *
 * @return a new TemplatedString
 */
public TemplatedString build() {
return new SimpleTemplatedString(Collections.unmodifiableList(fragments), Collections.unmodifiableList(values));
}

And SimpleTemplatedString is just:

record SimpleTemplatedString(List<String> fragments, List<Object> values) implements TemplatedString {}

There doesn't seem to be any defensive copying of the fragments and values lists, just wrapping in the unmodifiableList() call.  So it is unmodifiable but if a builder is reused I then I believe those lists could change.

var builder = TemplatedString.builder();
TemplatedString ts = builder
.fragment("a:").value(1)
.fragment(", b:").value(2)
.build();

String result = STR.apply(ts); // result = "a:1, b:2"

builder.fragment(", c:").value(3);
result = STR.apply(ts); // result = "a:1, b:2, c:3" - same TempaltedString, very different result

Is this behavior intended? Based on the documentation on TemplatedString I wouldn't have thought so, but perhaps I am missing something.

Thanks for your time.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220921/aefcefbb/attachment-0001.htm>


More information about the amber-dev mailing list