75 lines
2.0 KiB
Plaintext
75 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In Kotlin, `==` means structural equality and `!=` structural inequality and both map to the left-side term's `equals()` function.
|
|
It is, therefore, redundant to call `equals()` as a function.
|
|
Also, `==` and `!=` are more general than `equals()` and `!equals()` because it allows either of both operands to be `null`.
|
|
|
|
Developers using `equals()` instead of `==` or `!=` is often the result of adapting
|
|
styles from other languages like Java, where `==` means reference equality and `!=` means reference inequality.
|
|
|
|
=== What is the potential impact?
|
|
|
|
==== Wrong logic
|
|
|
|
`==` and `!=` allow either of both operands to be `null`, while `equals()` doesn't.
|
|
|
|
==== Readability and Understanding
|
|
|
|
The `==` and `!=` operators are a more concise and elegant way to test structural equality than calling a function.
|
|
|
|
== How to fix it
|
|
|
|
Replace `a.equals(b)` with `a == b`.
|
|
Replace `!a.equals(b)` with `a != b`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,kotlin]
|
|
----
|
|
data class Person(
|
|
val name: String,
|
|
val firstName: String,
|
|
val age: Int,
|
|
val address: String
|
|
)
|
|
----
|
|
|
|
[source,kotlin,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
fun checkEquality() {
|
|
val personA = Person("Claus", "Santa", 200, "North Pole")
|
|
val personB = Person("Nicholas", "Saint", 1700, "Myra")
|
|
if (personA.name.equals(personB.name)) { // Noncompliant, should use `==` instead
|
|
// ...
|
|
}
|
|
if (!personA.equals(personB)) { // Noncompliant, should use `!=` instead
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,kotlin,diff-id=1,diff-type=compliant]
|
|
----
|
|
fun checkEquality() {
|
|
val personA = Person("Claus", "Santa", 200, "North Pole")
|
|
val personB = Person("Nicholas", "Saint", 1700, "Myra")
|
|
if (personA.name == personB.name) { // Compliant
|
|
// ...
|
|
}
|
|
if (personA != personB) { // Compliant
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://kotlinlang.org/docs/operator-overloading.html#equality-and-inequality-operators[Kotlin Docs, Equality and inequality operators]
|
|
|