0

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?

James Baye
  • 43
  • 5

1 Answers1

2

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.

cfrick
  • 35,203
  • 6
  • 56
  • 68
  • Thanks, and reading up on this a bit more, I'm guessing that this is because `.indexOf` uses `.equals` internally. I had found by chance that `["${mystr}_bar", "baz"].findIndexOf{it -> it == "foo_bar"}` works. Now that I've read about the differences between `==`, `.equals`, `.compareTo` and `.is` this makes a lot more sense! – James Baye Jun 18 '21 at 21:22