Maybe stupid question, but I m wondering one thing...
# announcements
k
Maybe stupid question, but I m wondering one thing - is it smart to create a box for specialized array type in order to avoid having to override the
equals()
methods in each and every data class when I want to use one of these? 🤔 If so why such comparable variants of the spec. array types are not part of the STL yet? Obviously, I cannot use all the exension methods provided by the STL directly then.. but it still feels a bit better than messing up my domain model with all those overrides of equals() and hashCode() typically because of one single array field.. Something like this:
Copy code
class ComparableByteArray (val array: ByteArray) {
    val size: Int
        get() = array.size

    constructor(size: Int) : this(ByteArray(size))
    constructor(other: ComparableByteArray) : this(other.array.copyOf())

    override fun equals(other: Any?): Boolean =
        (this === other) || (javaClass == other?.javaClass && array.contentEquals((other as ComparableByteArray).array))
    override fun hashCode(): Int = array.contentHashCode()
    override fun toString(): String = array.toString()
    operator fun get(index: Int) = array[index]
    operator fun set(index: Int, value: Byte) = array.set(index, value)
    operator fun iterator(): ByteIterator = array.iterator()
}

data class User {
   //....,
   secretKey: ComparableByteArray
   //...,

   // <-- Would have to override equals() and hashCode() here if I used just ByteArray so the data class loses its purpose
}
r
First you can make that class implement Collection and get free extension functions
Second, why not just use List directly? Do you need exactly a ByteArray for some reason?
k
@randomcat thanks for reply.. right, Indeed I didnt notice that most of them are on collection.. because ByteArray apparently doest extend or implement anything
m
List would force all the bytes to be wrapped. Not sure what would happen if implementing Collection. Would be able to store them unwrapped, but I'm guessing the get and set methods would wrap.
k
For the second, it is mainly for perdormance reasons.. it just feels weird to box each and every byte
r
fair
m
I guess it’s not worth the effort to provide array wrappers with Kotlin’s stdlib. Once JVM supports inline classes then arrays support equals afaik 🤔