0

I have a quick question about Sets and custom objects in Kotlin. I have a simple 3D Point class and I would like to have a set of these.

class Point3D(val x: Int, val y: Int, val z: Int){

    override fun equals(other: Any?): Boolean {
        if (other == null) return false
        if (other is Point3D && (this.x != other.x || this.y != other.y || this.z != other.z)) return false
        return true
    }

    override fun toString(): String {
        return "Point(${this.x}, ${this.y}, ${this.z})"
    }
}

When I make a set, I can add several Points with identical coordinates. I tried to override the equality operator but that still doesn't seem to fix it. How can I avoid duplicate objects being added to sets?

  • You need to override hashCode() too. – lukas.j Feb 12 '22 at 11:32
  • You need to override `hashCode()` as well, but since you're using Kotlin just declare `Point3D` as a `data class`. Kotlin will generate respectful methods for you, no need to override anything. – Михаил Нафталь Feb 12 '22 at 11:36
  • I would recommend to use a 'data class' for this, then you do not implement the equals–hashCode-pair, it will be done automatically (https://kotlinlang.org/docs/data-classes.html). – lukas.j Feb 12 '22 at 11:36
  • `equals()` also needs to be adjusted to return false when called for objects that _aren't_ instances of Point3D. (The current implementation is neither symmetric nor transitive; see [the docs](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/equals.html).) It could be as simple as: `override fun equals(other: Any?) = other is Point3D && other.x == x && other.y == y && other.z == z`. – gidds Feb 12 '22 at 12:15

1 Answers1

0

Thanks guys, both reimplementing hashCode() and declaring data class worked