Groovy makes Java Strings mutable

23 04 2008

Just stumbled about an entry in the Groovy mailing list

def input = '''<tag id="12" />'''
def tag = new XmlParser().parseText(input)
tag.attribute("id").value = "ABCD"
println tag.attribute("id")
==>
AB

Oops. The object returned by tag.attribute(”id”) is of type String (i.e. java.lang.String) and not of some type XmlAttribute. And the ‘value’ is the private final (sic!) variable containing the String’s content (a char array). And Groovy allows us to change that value … making String mutable.

Even funnier:

...
println tag.attribute("id").value
==>
[A, B, C, D]

I always had the feeling, that Groovy was programmed first and then designed afterwards. In the last years they progressed nicely, but this makes me doubt again. This issue has been known since May 2007. But I think they just realized what it means: “Yikes! String is mutable!

Update (April, 24th): Created a new issue, because the existing issue is only concerned with violating the “private” contract and not with violating the “final” contract.

Please vote for the issue to be fixed.


Actions

Information

One response to “Groovy makes Java Strings mutable”

20 05 2008
pikapika (12:36:16) :


def input = ''''''
def tag = new XmlParser().parseText(input)
tag.attribute("id").value = "ABCD"
println tag.attribute("id").size()
println tag.attribute("id").each {print it}

even worse!

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>