Traits in Scala

 Traits in Scala


Traits in Scala are similar to interfaces in Java, but they can also include concrete method implementations. A class can extend multiple traits, allowing for flexible and modular code design. Here's an example:

kotlin


trait Shape {

  def area(): Double

}


class Rectangle(val width: Double, val height: Double) extends Shape {

  def area(): Double = width * height

}


class Circle(val radius: Double) extends Shape {

  def area(): Double = math.Pi * radius * radius

}


val rect = new Rectangle(5, 10)

println(s"The area of the rectangle is ${rect.area()}.")


val circle = new Circle(5)

println(s"The area of the circle is ${circle.area()}.")

This defines a Shape trait that has an abstract area method, and two classes that extend the trait and implement the method in different ways. The main method creates instances of both classes and calls the area method on each to get the area of the shapes.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...