Post Format

Groovy makes Java Strings mutable

1 comment

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.

1 Comment so far Join the Conversation


  1. 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!

    Reply

Leave a Reply

Required fields are marked *.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s