问题描述
我似乎无法弄清楚如何为自定义泛型集合编写 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] }
}
}
不给我任何警告