liveBook · Manning

..< operator

As explained in Kotlin in Action, 2E

The `..<` operator constructs a range that includes its lower endpoint and excludes its upper endpoint.

The `..<` operator constructs a half-open range: it includes the lower endpoint and excludes the upper endpoint. Use it when an ending coordinate or boundary should not belong to the range. section 9.3.2

Checking rectangle coordinates

data class Rectangle(val upperLeft: Point, val lowerRight: Point) operator fun Rectangle.contains(p: Point): Boolean { return p.x in upperLeft.x..<lowerRight.x && p.y in upperLeft.y..<lowerRight.y } val rect = Rectangle(Point(10, 20), Point(50, 50)) println(Point(20, 30) in rect) // true println(Point(5, 5) in rect) // false Here, x values run from 10 through 49 and y values from 20 through 49; the right and bottom boundaries are excluded. section 9.3.2

Compared with a closed range:

  • `10..20` includes 20, whereas `10..<20` includes values from 10 through 19. section 9.3.2
  • Combining `..<` with `in` expresses half-open membership checks directly. section 9.3.2
Listing 9.11 Implementing the in convention
data class Rectangle(val upperLeft: Point, val lowerRight: Point)
 
operator fun Rectangle.contains(p: Point): Boolean {
    return p.x in upperLeft.x..<lowerRight.x &&        #1
           p.y in upperLeft.y..<lowerRight.y           #2
}
 
fun main() {
    val rect = Rectangle(Point(10, 20), Point(50, 50))
    println(Point(20, 30) in rect)
    // true
    println(Point(5, 5) in rect)
    // false
}

Inspect the complete `Rectangle.contains` implementation and its membership checks. section 9.3.2

How Kotlin in Action, 2E covers it

How deep it goes
Defines half-open ranges, contrasts them with closed ranges, and stops at membership use rather than implementation internals.
Examples
Uses a `Rectangle` whose x and y coordinates are tested with half-open ranges.
What it assumes
Assumes familiarity with ranges and the `in` operator; contrasts closed ranges with open ranges.
What you can do after
Apply it to define coordinate or membership boundaries that exclude their ending point.
How it connects
Connects ranges with the `in` operator, the `contains` function, and rectangle coordinate boundaries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.