3

I stumbled across some strange behaviour when comparing Java8 time objects. The below does not appear to be valid code.

val t1 = LocalTime.now()
val t2 = LocalTime.now()
val foo: Int = t1 > t2

Yet hovering over the undersquiggled code shows that the overridden function return type is correct:

enter image description here

Any ideas?

1
  • 2
    t1 > t2 returns a boolean. The > operator uses compareTo under the hood, but it's not compareTo. Commented Apr 14, 2022 at 23:22

1 Answer 1

2

According to the documentation, when using the natively overloaded operators (comparison operators specifically) - Kotlin doesn't just call compareTo but rather performs a compareTo against 0 (thus ending up as a bool).

https://kotlinlang.org/docs/operator-overloading.html#comparison-operators

Comparison operators

Expression Translated to
a > b a.compareTo(b) > 0
a < b a.compareTo(b) < 0
a >= b a.compareTo(b) >= 0
a <= b a.compareTo(b) <= 0

All comparisons are translated into calls to compareTo, that is required to return Int.

The documentation snippet you attached is admittedly a bit confusing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.