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 an open range: it includes the lower endpoint and excludes the upper endpoint. For example, `10..<20` contains `10` through `19`, whereas the closed range `10..20` also contains `20`. Use `..<` when an ending coordinate or boundary must remain outside the range. section 9.3.2

Checking points inside a rectangle

A rectangle can exclude its bottom and right edges by testing each coordinate against an open range: ```kotlin operator fun Rectangle.contains(p: Point): Boolean { return p.x in upperLeft.x..<lowerRight.x && p.y in upperLeft.y..<lowerRight.y } ``` Here `p.x` must be at least `upperLeft.x` but less than `lowerRight.x`; the same rule applies to `p.y`. A point on the right or bottom boundary is therefore outside the rectangle. section 9.3.2

This boundary rule works naturally with `in`: each coordinate is checked for membership in the range. It avoids treating the ending coordinate as part of a rectangle whose bottom and right coordinates are defined as exclusive. 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 inside/outside point checks. section 9.3.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains endpoint inclusion and applies the operator in a two-coordinate containment check.
Examples
Uses `10..<20` and a `Rectangle.contains` implementation for point membership.
What it assumes
Assumes familiarity with range notation and `in` membership checks.
What you can do after
Apply it via Kotlin ranges to exclude an ending coordinate from membership tests.
How it connects
Connects open ranges to closed ranges, the `in` operator, and `contains`.

Also explained in

Compare how 7 books explain operator →

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.