w3resource

Scala Program: Triangle class with equilateral check

Scala OOP Exercise-9 with Solution

Write a Scala program that creates a class Triangle with properties side1, side2, and side3. Implement a method isEquilateral to check if the triangle is equilateral.

Sample Solution:

Scala Code:

class Triangle(val side1: Double, val side2: Double, val side3: Double) {
  def isEquilateral(): Boolean = {
    side1 == side2 && side2 == side3
  }
}

object TriangleApp {
  def main(args: Array[String]): Unit = {
    val triangle1 = new Triangle(6.0, 6.0, 6.0)
    val triangle2 = new Triangle(3.0, 4.0, 5.0)

    println(s"Triangle 1 is equilateral: ${triangle1.isEquilateral()}")
    println(s"Triangle 2 is equilateral: ${triangle2.isEquilateral()}")
  }
}

Sample Output:

Triangle 1 is equilateral: true
Triangle 2 is equilateral: false

Explanation:

In the above exercise,

  • The "Triangle" class is defined with a constructor that takes side1, side2, and side3 as parameters and initializes the corresponding properties. The properties are defined as val, making them read-only.
  • The "isEquilateral()" method is defined in the Triangle class. It checks if all three sides of the triangle are equal, indicating an equilateral triangle.
  • The "TriangleApp" object contains the main method to test functionality. It creates instances of Triangle with different side lengths, and calls the isEquilateral method to check if the triangles are equilateral.

Scala Code Editor :

Previous: Animal class with make sound method.
Next: Resizable Trait with rectangle class implementation.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/oop/scala-oop-exercise-9.php