hashCode

override fun hashCode(): Int

Returns a hash code value for this decimal.

This function follows the contract of Any.hashCode, with an additional property: if two instances of Decimal are not equal, then calling this function on these objects must produce different hash codes.


Calling from Kotlin

Here's an example of calling this function from Kotlin code:

fun checkEquality(decimal: Decimal, other: Any?) {
check(decimal == other)
check(decimal.hashCode() == other.hashCode())
}

fun checkDiff(decimal: Decimal, other: Any?) {
check(decimal != other)
check(decimal.hashCode() != other.hashCode())
}

// Scale-normalised values are equal:
checkEquality(
decimal = Decimal.fromLong(0),
other = Decimal.parse("-0.0")
)
checkEquality(
decimal = Decimal.parse("3.14"),
other = Decimal.parse("3.140")
)
checkEquality(
decimal = Decimal.parse("-2.5"),
other = Decimal.parse("-2.50")
)

// Different values or types are not equal:
checkDiff(decimal = Decimal.fromLong(0), other = Decimal.fromLong(1))
checkDiff(decimal = Decimal.parse("3.14"), other = 3.14)
checkDiff(decimal = Decimal.fromLong(-42), other = null)

Calling from Java

Here's an example of calling this function from Java code:

final BiConsumer<Decimal, Object> checkEquality = (decimal, other) -> {
final boolean equality = Objects.equals(decimal, other);
final boolean hashConformity =
Objects.hashCode(decimal) == Objects.hashCode(other);
final boolean check = equality && hashConformity;
if (!check) throw new IllegalStateException("Check failed.");
};

final BiConsumer<Decimal, Object> checkDiff = (decimal, other) -> {
final boolean equality = !Objects.equals(decimal, other);
final boolean hashConformity =
Objects.hashCode(decimal) != Objects.hashCode(other);
final boolean check = equality && hashConformity;
if (!check) throw new IllegalStateException("Check failed.");
};

// Scale-normalised values are equal:
checkEquality.accept(Decimal.fromLong(0), Decimal.parse("-0.0"));
checkEquality.accept(Decimal.parse("3.14"), Decimal.parse("3.140"));
checkEquality.accept(Decimal.parse("-2.5"), Decimal.parse("-2.50"));

// Different values or types are not equal:
checkDiff.accept(Decimal.fromLong(0), Decimal.fromLong(1));
checkDiff.accept(Decimal.parse("3.14"), 3.14);
checkDiff.accept(Decimal.fromLong(-42), null);