Methods in Scala

Our example demonstrates how to define and use methods in Scala. Here’s the translated code and explanation:

class Rect(val width: Int, val height: Int) {
  // This `area` method is defined within the class
  def area(): Int = {
    width * height
  }

  // Methods can be defined for either the class or its instances
  def perim(): Int = {
    2 * width + 2 * height
  }
}

object Methods {
  def main(args: Array[String]): Unit = {
    val r = new Rect(10, 5)

    // Here we call the 2 methods defined for our class
    println("area: " + r.area())
    println("perim: " + r.perim())

    // Scala doesn't distinguish between value and reference types for method calls
    // So there's no need for explicit pointer handling
    println("area: " + r.area())
    println("perim: " + r.perim())
  }
}

In Scala, methods are defined within classes or objects. Unlike some other languages, Scala doesn’t have a separate concept of “receiver types” - methods are always associated with the class or object they’re defined in.

The Rect class is defined with two parameters, width and height, which are automatically turned into fields of the class due to the val keyword.

The area and perim methods are defined within the Rect class. They can access the class fields directly.

In the main method of the Methods object, we create an instance of Rect and call its methods.

Scala automatically handles access to methods, regardless of whether you’re dealing with the object itself or a reference to it. There’s no need for explicit pointer handling or method call syntax differences between value and reference types.

To run this program, you would typically save it in a file named Methods.scala, compile it with scalac Methods.scala, and then run it with scala Methods. The output would be:

area: 50
perim: 30
area: 50
perim: 30

Scala’s object-oriented features, combined with its functional programming capabilities, provide a powerful and flexible way to structure code and define behavior.