`indexOf` returns unexpected result on list of groovy.Gstrings

113 Views Asked by At

When running indexOf on a list of Gstrings, the return value is always -1 despite an expected index match:

mystr = "foo"

// expect .indexOf to return 0
println "${["${mystr}_bar", "baz"].indexOf("foo_bar")}" // -1
println "${[mystr + "_bar", "baz"].indexOf("foo_bar")}" // ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​0​​​​​​​​​​​​​​

Am I misunderstanding something or is this a bug?

1

There are 1 best solutions below

1
cfrick On BEST ANSWER

You would have to use:

["${mystr}_bar".toString(), "baz"].indexOf("foo_bar")
// or if you have many: ["${mystr}_bar", "baz"]*.toString().indexOf("foo_bar")

(note the explicit .toString() there).

GString look the same (e.g. they .toString() to their current state) like String, but they aren't. E.g. you can have a closure inside a GString or a call to generate a random number. They are not immutable or "stable" like their String brothers. That e.g. is also the reason, why they are unfit to be keys in maps. So they equal the same, but they hash different.