I just cannot override hashCode() function on value class. minimal example (I know that in this example there is no need to override it...)
@JvmInline
value class Identifier(val value: String){
override fun hashCode(): Int = this.value.hashCode()
}
I get error: Member with the name 'hashCode' is reserved for future releases
Edit: Is there any way to specify own hashCode() function?
As of right now, you cannot override the
equals
orhashCode
method of value classes. The language specification explicitly disallows this:This is because the developers of Kotlin are planning to add a strongly typed
equals
method that you can override.From the inline classes proposal:
This is so that when you use
==
on value classes with a customequals
, you don't have to box them every time as you are passing it to theAny?
parameter on theAny.equals
method. The compiler would also automatically generate anequals(Any?)
implementation from yourequals(Identifier)
implementation.But they haven't implemented this feature yet. This is why they don't let you implement
hashCode
- because if you do, you would most likely also need to implementequals(Any?)
(it is rarely useful/correct to just implementhashCode
), but that means your code would break in future versions of Kotlin! In future versions, you would need to implementequals(Identifier)
, notequals(Any?)
.So you can only wait until this feature gets added. Until then, you cannot have
hashCode
andequals
that does not delegate to the wrapped value.