Start learning free

LESSON 252 OF 573 · FUNCTIONS & CLASSES

Rectangle Class in Kotlin: Properties and Methods

Practice O(1) Read the full explanation

A class bundles some values with the questions you can ask about them. Write a class Rectangle that remembers a rectangle's width and height, and can tell its area, its perimeter, and whether it is a square.

Implement the class Rectangle:

  • Rectangle(width, height) creates a rectangle with the given sizes.
  • area() returns the area of the rectangle: its width times its height.
  • perimeter() returns the perimeter: the length all the way around, twice the width plus twice the height.
  • isSquare() returns true if the width and the height are equal, and false otherwise.

Each line of the input is one rectangle: its width and its height. The test code first creates a Rectangle for every line, then asks each of them, in order, for its area, its perimeter and whether it is a square, and prints the three answers on one line, the boolean as True or False. So each object must keep its own sizes. The starter code spells these names the way your language does (in Go and Rust, Rectangle is a struct with methods).

 

Example 1:

Input:
    Rectangle(3, 4)
Output: 12 14 False
Explanation: The area is 3 · 4 = 12. Going around, the sides are 3 + 4 + 3 + 4 = 14.
The width and the height differ, so it isn't a square.

Example 2:

Input:
    Rectangle(5, 5)
Output: 25 20 True
Explanation: 5 · 5 = 25, and 4 sides of 5 make 20. Both sizes are 5: a square is a rectangle with equal sides.

Example 3:

Input:
    Rectangle(2, 10)
    Rectangle(10, 2)
Output:
20 24 False
20 24 False
Explanation: Two objects, each with its own sizes. Turning a rectangle on its side changes neither its area nor its perimeter.

 

Constraints:

  • 1 <= width, height <= 104
  • At most 10 rectangles per test.

Note:

Each method needs only the two sizes, so each one runs in O(1) time.

STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · FUNCTIONS & CLASSES

    Rectangle Class in Kotlin, explained

    Problem overview

    A class bundles some values with the questions you can ask about them. Here the values are a rectangle's width and height, and the questions are its area, its perimeter and whether it is a square. You write the class Rectangle; the lesson's tests create several rectangles and ask each one the three questions.

    Each object keeps its own sizes. A Rectangle(3, 4) has area 12, perimeter 14 and is not a square. A Rectangle(5, 5) has area 25, perimeter 20 and is a square. A rectangle that is 2 wide and 10 high and one that is 10 wide and 2 high both have area 20 and perimeter 24: turning a rectangle on its side changes neither.

    How the class is built

    The class header already declares the two sizes: class Rectangle(val width: Int, val height: Int). Writing val inside the parentheses does two jobs at once. The two names are the constructor's parameters, and they also become properties of every object. You don't write a separate field or an assignment. Inside any method, width and height mean the properties of the object the method was called on.

    Each method needs only those two numbers, so each one takes constant time.

    Step by step

    1. area. A 3 by 4 rectangle is 3 rows of 4 unit squares, so the area is width times height.
    2. perimeter. Walking around the rectangle you pass each side once: width, height, width, height. That is 2 * (width + height). The parentheses make the addition happen first.
    3. isSquare. A comparison with == is already a Boolean, true exactly when the two sizes are equal. No if is needed.

    The solution in Kotlin

    class Rectangle(val width: Int, val height: Int) {
        fun area(): Int {
            return width * height
        }
    
        fun perimeter(): Int {
            return 2 * (width + height)
        }
    
        fun isSquare(): Boolean {
            return width == height
        }
    }
    

    Two Kotlin details are worth knowing here:

    • width == height compares values. In Kotlin == calls equals, and for Int that means the numbers are equal. (=== is the one that compares references.)
    • Int is a 32-bit number. The lesson keeps both sizes at or below 10,000, so even the largest perimeter, 40,000, and the largest area, 100,000,000, fit comfortably.

    Using the class

    You create an object by calling the class name like a function, with no new. Then you call the methods with a dot:

    fun main() {
        val a = Rectangle(3, 4)
        println("${a.area()} ${a.perimeter()} ${a.isSquare()}")
    
        val b = Rectangle(5, 5)
        println("${b.area()} ${b.perimeter()} ${b.isSquare()}")
    
        val c = Rectangle(2, 10)
        val d = Rectangle(10, 2)
        println("${c.area()} ${c.perimeter()} ${d.area()} ${d.perimeter()}")
    }
    

    It prints:

    12 14 false
    25 20 true
    20 24 20 24
    

    Kotlin prints booleans as true and false; the lesson's tests show them as True and False, so don't worry about that spelling in your own code.

    Common mistakes

    • Forgetting the parentheses in the perimeter. 2 * width + height doubles only the width. The height is then added only once, so the result is wrong for almost every rectangle.
    • Writing val or var again in the body. The header already created the properties. Declaring new ones inside a method would make local variables that hide them.
    • Using an if for isSquare. if (width == height) return true else return false works, but return width == height says the same thing directly.
    • Calling a method without parentheses. a.area is not a call. Write a.area().
    Keep going with Kotlin500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free