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] }
    }   
}

不给我任何警告

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...