Karlo Lozovina
05/27/2020, 2:43 PMspand
05/27/2020, 2:48 PMopen class Base {
init {
check(this::class.isData)
}
}
dany
05/27/2020, 2:49 PMfun equals(other: MyType)
in your interrfaceKarlo Lozovina
05/27/2020, 2:53 PMCasey Brooks
05/27/2020, 3:00 PMequals
and hashCode
. You can put those functions in your interface, which will require implementing classes to define them (and not just use the default ones from Any
)
interface StructuralEquality {
override fun equals(other: Any?): Boolean
override fun hashCode(): Int
}
// does not compile
class ClassThatDoesNotImplementEqualsAndHashcode(val a: String) : StructuralEquality {
}
// compiles
class ClassThatImplementsEqualsAndHashcode(val a: String) : StructuralEquality {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ClassThatImplementsEqualsAndHashcode
if (a != other.a) return false
return true
}
override fun hashCode(): Int {
return a.hashCode()
}
}
// compiles
data class DataClassThatImplementsEqualsAndHashcode(val a: String) : StructuralEquality
Karlo Lozovina
05/27/2020, 3:03 PMKarlo Lozovina
05/27/2020, 3:04 PMKarlo Lozovina
05/27/2020, 3:04 PMMatteo Mirk
05/27/2020, 3:05 PMKarlo Lozovina
05/27/2020, 3:06 PMJakub Pi
05/27/2020, 3:06 PMKarlo Lozovina
05/27/2020, 3:06 PMKarlo Lozovina
05/27/2020, 3:07 PMKarlo Lozovina
05/27/2020, 3:07 PMMatteo Mirk
05/27/2020, 3:11 PMilya.gorbunov
05/27/2020, 7:55 PMYou can put those functions in your interface, which will require implementing classes to define themThis is rather questionable behavior of the compiler and we may change it later. See https://youtrack.jetbrains.com/issue/KT-24971
Karlo Lozovina
05/27/2020, 8:06 PMSam Garfinkel
05/28/2020, 2:47 AMKClass<*>.isData
is based on Kotlin-specific metadata and is a pretty big antipattern.