首页 > 解决方案 > 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>我会收到一个警告,这很烦人。
有没有办法在没有警告或错误的情况下正确处理这种情况?

标签: kotlingenericsequals

解决方案


如果你检查

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

没有给我任何警告


推荐阅读