[英]Kotlin equals on custom generic class
我似乎無法弄清楚如何為自定義通用集合編寫 equals function 。
class 包含通用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
但是語言沒有給我任何選擇。
如果我將 object 轉換為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] }
}
}
沒有給我任何警告
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.