How to implement calculating hashcode from a class...
# kotlin-native
m
How to implement calculating hashcode from a class declared fields and checking if classes are equal? For JVM it was implemented used reflection, but I have no idea how to do the same thing for Kotlin Native. Maybe there is a better solution to implement these functions without reflection? Abstract Common:
Copy code
interface Event
Copy code
expect abstract class BleDataEvent() : Event {
    var isValidFrame: Boolean
        protected set

    override fun hashCode(): Int
    override fun equals(other: Any?): Boolean
    override fun toString(): String
}
Android Implementation
Copy code
actual abstract class BleDataEvent actual constructor() : Event {
    actual var isValidFrame = false
        protected set

    private fun fieldsHashCodes(): IntArray? {
        val fields: Array<Field>? = this.javaClass.declaredFields
        var fieldsValue: IntArray? = null
        if (fields != null && fields.isNotEmpty()) {
            fieldsValue = IntArray(fields.size)
            for (i in fields.indices) {
                try {
                    fieldsValue[i] =
                        17 * fields[i].name.hashCode() + 13 * fields[i].get(this).hashCode()
                } catch (ignored: Exception) {
                    fieldsValue[i] = 0
                }
            }
        }
        return fieldsValue
    }

    actual override fun hashCode(): Int {
        var hashCode = 1
        val fieldsHashCodes = fieldsHashCodes() ?: return super.hashCode()
        for (hash in fieldsHashCodes) {
            hashCode = hashCode * 41 + hash
        }
        return hashCode
    }

    actual override fun equals(other: Any?): Boolean {
        if (other == null) return false
        if (this === other) return true
        if (this.javaClass != other.javaClass) return false
        val bleDataFrameObj = other as BleDataEvent
        return this.hashCode() == bleDataFrameObj.hashCode()
    }

    actual override fun toString(): String {
        val builder = StringBuilder()
        val fields: Array<Field>? = this.javaClass.declaredFields
        builder.append(javaClass.simpleName).append("{\r\n")
        if (fields != null && fields.isNotEmpty()) {
            for (field in fields) {
                if (Modifier.isTransient(field.modifiers)) {
                    continue
                }

                builder.append(field.name).append(": ")
                try {
                    field.isAccessible = true
                    if (field.get(this) != null) {
                        builder.append(field.get(this).toString())
                    }
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                } catch (e: NullPointerException) {
                    e.printStackTrace()
                }

                builder.append("\r\n")
            }
        }
        builder.append("}")
        return builder.toString()
    }
}