Just throwing this out there, does anyone think it...
# stdlib
r
Just throwing this out there, does anyone think it would be a good idea to include such a function in std-lib:
Copy code
inline infix fun Any?.hash(other: Any?): Int = hashCode() * 31 + other.hashCode()
It would simplify writing
hashCode
functions:
Copy code
class ABC<A, B, C>(val a: A, val b: B, val c: C) {
    override fun hashCode() = a hash b hash c
}
👍 7
You could also add some overloads for primitives, but that would quickly explode.
b
I like the idea, but I’m not sure if this will be used. In my experience 95% of
hashCode
functions I use are from data classes. Also with a good IDE you will just auto generate the
hashCode
function in any case.
r
That's fair (I disagree about the 95%, but that's probably pretty domain specific)
s
Any particular reason you dont use
Objects.hash
?
k
Overhead, it creates a temporary array.
👍 2
s
I would be surprised if varargs arent heavily optimised on both the jvm and js
In any case.. I would heavily prefer a global
hash
with agressive compiler inline and unroll than another
Any?
extension. Just my two cents. Would be shorter to write also
Your implemention would also box any primitives I think
r
Yes, thus my first comment
s
Ah sorry. It was collapsed here.
👍 1
z
One more argument for doing this is that data classes are effectively useless for library APIs: https://jakewharton.com/public-api-challenges-in-kotlin/
b
You can work around the problem with the
copy
function by providing a custom copy function that calls the generated one, you just need to annotate it with
@Deprecated("", level = DeprecationLevel.HIDDEN)
. I don’t know a workaround for
componentN
except for only adding new properties to the end. That said, I don’t like the fact that kotlin adds
componentN
functions to all data classes automatically. Since they aren’t named, they just pose to much of a risk IMO. Especially when the data class is provided by a library.