Overloading == with different types of operands

The compiler error message is Operator ‘==’ cannot be applied to ‘Num’ and ‘Int’

… and, surprising as it may be, it does the Right Thing.

Equality in Kotlin is modeled very closely to object equality in Java, which is required for interoperability.
Values are compared using method equals, which is defined in kotlin.Any (and java.lang.Object).
This equality is used, for example, in standard collections, where values can be stored in sets or used as keys in maps.

Now, consider your class Num. It can’t be equal (in the terms above) to other number representations on JVM platform (java.lang.Integer, java.math.BigInteger, java.math.BigDecimal, to name a few), because these classes know nothing about Num. Even if you define equals for Num so that , for example, Num(1).equals(Integer(1)), it wouldn’t be symmetric: Integer(1).equals(Num(1)) will, of cause, return false. This will cause a whole lot of problems for everyone who relies on requirements for method equals, starting from standard collections.

That’s why, for example,

BigInteger.ONE.equals(Integer(1))
=> false

TL;DR: don’t do that, it will break a hole in time-space continuum.

2 Likes