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
