== operator is not equivalent to equals() function

I have a case where using the == operator will not yield the same result as invoking the equals() function when kotlin is compiled to JS. Shouldn’t these always yield the same result? Even IntelliJ tells me that I should replace the invocation of equals with the operator.

The only difference I know of is that equals could be applied to any type while == checks if the type is the same. Is this the problem? It was discussed somewhere earlier.

The type is definitely the same. It is 2 instances of the same data class that are equal per equals function. However, the == operator / equals function is invoked on a generic type parameter. Maybe that’s the cause. It looks like a compiler bug to me.

@fatjoe79 can you reproduce it with a minimal code sample / project?

1 Like

While producing the minimal code sample, I found out that the dynamic type is causing this behavior. This is the sample:

data class D(val s: String)

fun test(d1: dynamic, d2: dynamic) {
    console.log("d1 == d2", d1 == d2)
    console.log("d1.equals(d2)", d1.equals(d2))
}

val d1 = D("foo")
val d2 = D("foo")
test(d1, d2)

This will print

d1 == d2 false
d1.equals(d2) true

Is this expected behavior of dynamic types?

Operation a == b is translated to a?.equals(b) ?: (b === null)

Exceptions are:

  • Float and Double types follow IEEE 754 semantic: floating-point-numbers-equality
  • Expressions using values of dynamic type are translated to JavaScript “as is”, and do not use the Kotlin operator conventions.

Looks like a bug in IDE intentions

2 Likes

Expressions using values of dynamic type are translated to JavaScript “as is”, and do not use the Kotlin operator conventions

Sounds fair, but maybe IntelliJ should not suggest to replace equals with the operator in this case.

I understand that using dynamic is hacky for itself.

Unlike my minimal code sample, I have a type-safe generic API which internally uses dynamic to simplify its implementation. To the outside the API is perfectly type-safe.

Filed IDE intention issue: KT-28773

1 Like