Reputation: 9913
I'm implementing a pure Kotlin library that I will be releasing under an open source license. In my library I have, say, class A
, in which I want to override equals()
. I used Android Studio's auto-generator to do this, but it included a reference to javaClass
:
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as A
...
}
Is this reference safe to use in a pure Kotlin library? What will be the effect if somebody used my library to target, say, JavaScript? Is there a pure-Kotlin alternative to javaClass
? I'd like to avoid something like
if (other !is A) ...
because I don't want subclasses of A to register.
Upvotes: 1
Views: 358
Reputation: 17701
What you did is not safe. The reason Android Studio generated this code, is because you're not developing a multiplatform project, actually.
Multiplatform version would look like this:
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
return true
}
If your goal is to have a platform-agnostic library, develop it as multiplatform project, and put most of your code under common
module.
Upvotes: 4