Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proposed change of `equals` to `==` can't be applied to Char and String?

Tags:

kotlin

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?

like image 854
Elye Avatar asked Jan 26 '23 07:01

Elye


1 Answers

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.

like image 145
Joffrey Avatar answered Feb 16 '23 00:02

Joffrey