How to check if a point is inside a rectangle in Kotlin

1 Answer

0 votes
data class Point(val x: Double, val y: Double)

data class Rectangle(val topLeft: Point, val bottomRight: Point)

fun isPointInsideRectangle(p: Point, rect: Rectangle): Boolean {
    return p.x in rect.topLeft.x..rect.bottomRight.x &&
           p.y in rect.topLeft.y..rect.bottomRight.y
}

fun main() {
    val rect = Rectangle(Point(0.0, 0.0), Point(7.0, 7.0))
    val p = Point(3.0, 2.0)

    if (isPointInsideRectangle(p, rect)) {
        println("The point is inside the rectangle.")
    } else {
        println("The point is outside the rectangle.")
    }
}

 
  
/*
run:
  
The point is inside the rectangle.

*/

 



answered Jun 22, 2025 by avibootz
...