TemplatedString.builder() produces mutable TemplateString?
Nathan Walker
nathan.h.walker at gmail.com
Wed Sep 21 01:57:56 UTC 2022
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/20220920/d3b0e5a9/attachment.htm>
More information about the amber-dev
mailing list