kotlin - Kotlin 等于自定义泛型类
问题描述
我似乎无法弄清楚如何为自定义泛型集合编写 equals 函数。
该类包含一个泛型data: Array<T>
作为字段
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as CustomCollection<*>
if (size != other.size) return false
return (0 until size).all { data[it] == other.data[it] }
}
这失败并出现以下错误:Unsupported Array Nothing in return type is illegal
但是语言没有给我任何选择。
如果我将对象投射到CustomCollection<Any>
我会收到一个警告,这很烦人。
有没有办法在没有警告或错误的情况下正确处理这种情况?
解决方案
如果你检查
// not this
if (other == null || this::class != other::class) return false
//but:
if (other == null || other !is CustomCollection<*>) return false
class CustomCollection<T>(private val data: Array<T>) {
val size
get() = data.size
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is CustomCollection<*>) return false
if (size != other.size) return false
/* this will return true if [other] has a longer array that has the same
* start, not sure if you want that, consider
*/
// return data.contentEquals(other.data)
return (0 until size).all { data[it] == other.data[it] }
}
}
没有给我任何警告
推荐阅读
- react-native - 如何使用标签导航器在一页中创建两个抽屉
- java - 尝试使用 sendkeys 无法上传文件?
- postgresql - 如何在 postgres 结束后立即刷新物化视图
- wordpress - PHP Mailer(可重复使用的表单)- 使用 Wordpress:效果很好,除了文件附件
- apache-kafka - kafka-consumer-groups 命令问题
- pytorch - Pytorch 不使用 GPU 。在 Fastai 工作
- android-studio - android studio 错误“无法下载 builder.jar”
- mysql - 查找唯一列的计数
- php - 从多维数组php创建不同的数组集
- java - 表未映射休眠