I have a function as below.
fun process(string: String?): Int {
if (string != null) {
return string.filter { it.equals("a") }.length
}
return 0
}
It shows that it.equals("a")
could be improved, with the message
Call replaceable with binary operator
So I just use Alt-Enter
to change it accordingly and get
fun process(string: String?): Int {
if (string != null) {
return string.filter { it == "a" }.length
}
return 0
}
Unfortunately now it error stating
Operator '==' cannot be applied to Char and String
.
I assume this is a bug in the proposed optimization?
Just to be sure we're on the same page, it
is a Char
because the filter
method that you use operates on the string as a sequence of characters.
Therefore, it.equals("a")
is effectively comparing a Char
with a String
. This can never be true, because a string can never be equal to any character, even if it contains only one. So the code doesn't work in either case, unless you change your string "a"
to the character 'a'
.
Even if the operator ==
is compiled to the equivalent equals()
method call, the compiler has additional checks in the operator form compared to explicit method calls. The error you get is because the ==
operator requires a type match, as opposed to its method counterpart equals()
. (Since "a"
is a string, you can't use the operator to compare it with the character it
).
Why the difference? You may ask.
As far as I understood, the Kotlin team followed the Java convention for the method equals
and left its contract permissive by allowing Any?
as parameter. This is probably because of constraints of interoperability with Java.
However, they still saved us from this kind of mistakes with the additional type safety of the operator.
I have to admit, though, that the IDE should give you a warning for your incorrect equals
call before asking you to replace the method call by an operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With