Methods in Modelica

Modelica supports methods defined on class types.

model Rectangle
  parameter Real width;
  parameter Real height;
  
  function area
    output Real result;
  algorithm
    result := width * height;
  end area;
  
  function perimeter
    output Real result;
  algorithm
    result := 2 * width + 2 * height;
  end perimeter;
end Rectangle;

model Methods
  Rectangle r(width=10, height=5);
equation
  when initial() then
    Modelica.Utilities.Streams.print("area: " + String(r.area()));
    Modelica.Utilities.Streams.print("perimeter: " + String(r.perimeter()));
  end when;
end Methods;

In this example, we define a Rectangle model with width and height parameters. The area and perimeter functions are defined within the Rectangle model, which is similar to methods in other object-oriented languages.

The area function calculates and returns the area of the rectangle, while the perimeter function calculates and returns the perimeter.

In the Methods model, we create an instance of Rectangle with width 10 and height 5. We then use the when initial() construct to print the area and perimeter at the start of the simulation.

To run this Modelica code, you would typically use a Modelica simulation environment. The output would look something like this:

area: 50
perimeter: 30

In Modelica, there’s no direct equivalent to Go’s pointer receivers or value receivers. All variables in Modelica are references by default, and the language handles the details of memory management automatically.

Modelica’s approach to object-oriented programming is somewhat different from languages like Go or Java. It uses equation-based modeling, which is particularly well-suited for describing physical systems and their behavior over time.

Next, we’ll look at Modelica’s mechanism for defining interfaces and abstract classes, which serve a similar purpose to Go’s interfaces in terms of defining common behavior across different types.