Proposal for Chained Comparison Operators in Kotlin

I would like to propose the addition of chained comparison operators to the Kotlin programming language. Chained comparison operators allow for more concise and expressive code when comparing multiple values in a sequence.

Motivation:

Currently, when we need to compare multiple values in a sequence, we often resort to using multiple logical AND (&&) operators, which can make code harder to read and maintain. Chained comparison operators would simplify such comparisons and enhance code clarity.

Syntax Proposal:

I suggest introducing the following syntax for chained comparison operators:

a < b < c < d

This syntax would allow developers to chain comparison operations without the need for multiple && operators.

Examples:

// Current approach
if (a < b && b <= c && c == d) {
    // Do something
}

// With chained comparison operators
if (a < b <= c == d) {
    // Do something
}

Benefits:

  • Improved code readability: Chained comparison operators make it easier to understand and write code that involves multiple comparisons.
  • Reduced verbosity: Developers can write concise code without the need for excessive logical operators.
  • Potential for optimization: The Kotlin compiler could potentially optimize chained comparisons for improved performance.
1 Like

Isn’t this backward incompatible? a < b <= c == d is currently interpreted as (((a < b) <= c) == d, which is a different thing than a < b && b <= c && c == d.

4 Likes

It is an exotic feature in programming langauges. Among the major ones, only Python supports chained comparisons. Most of the time it is used for the range checks like a <= x <= b which reads in the wrong order, as the object of the comparison here is x, which you are checking for its belonging into the range a..b. In Kotlin it is expressed in a more direct form of x in a..b, which reads better, because it puts the object of the operation to the front.

5 Likes