Even if it was called for each iteration how would kotlin know which entry was removed? You could avoid an IndexOverflowException but there would be no way to guarantee that you wouldn’t skip any element. Iterating over lists that are changed at the same time is hard and there is no default way to do it since you could add/remove elements anywhere.
If you want to use a loop instead of @naxymatt’s version you could use while(stringBuilder2.isNotEmpty)
and then always remove the first character. Also you can stop the loop early if you can’t remove a char, because you already know at that point that the string isn’t an anagarm.
Also you don’t need to use a.equals(b)
in kotlin. Kotlin doesn’t treat ==
like java does.
If you compare java and kotlin equals you get the following
Kotlin | Java |
---|---|
a == b | a.equals(b) |
a === b | a == b |