密封数据类不考虑相等中的父属性



考虑以下内容:

sealed class MySealedClass(val guid: String = UUID.randomUUID().toString()) {
data class MyDataClass(var title: String) : MySealedClass()
data class MyDataClass2(var something: String) : MySealedClass()
}
val instance1 = MySealedClass.MyDataClass("hello")
val instance2 = MySealedClass.MyDataClass("hello")
Timber.i("instance1 guid: ${instance1.guid}")
Timber.i("instance2 guid: ${instance2.guid}")
Timber.i("are instances equal? ${instance1 == instance2}")
// Output:
instance1 guid: <removed>eb
instance2 guid: <removed>a6 // note that instance 2 GUID is different!
are instances equal? true   // yet the instances are considered equal

似乎来自父类MySealedClass的guid属性在为数据类生成的equals()方法中没有被考虑。我怎样才能确保它被考虑?有没有办法不触及生成的equals()方法?

当生成equals/hashCode/toString时,Kotlin中的数据类只使用主构造函数中列出的属性(参见文档)。所以,为了将guid包含到生成的方法实现中,并将其作为构造函数参数传递:

data class MyDataClass(
var title: String, 
override val guid: String = UUID.randomUUID().toString()
) : MySealedClass()

相关内容

  • 没有找到相关文章

最新更新