Methods in Dart

Dart supports methods defined on class types.

import 'dart:math';

class Rectangle {
  int width;
  int height;

  Rectangle(this.width, this.height);

  // This `area` method is defined on the Rectangle class.
  int area() {
    return width * height;
  }

  // Methods can be defined for either the class or its instances.
  // Here's an example of an instance method.
  int perimeter() {
    return 2 * width + 2 * height;
  }
}

void main() {
  var r = Rectangle(10, 5);

  // Here we call the 2 methods defined for our class.
  print('area: ${r.area()}');
  print('perimeter: ${r.perimeter()}');

  // Dart automatically handles method calls on instances.
  // There's no need to explicitly use pointers or references.
  print('area: ${r.area()}');
  print('perimeter: ${r.perimeter()}');
}

To run the program:

$ dart run methods.dart
area: 50
perimeter: 30
area: 50
perimeter: 30

In Dart, classes are used to create objects that bundle data and methods that operate on that data. Methods are functions that are associated with a class or object.

Unlike Go, Dart doesn’t have a concept of pointer and value receivers. All objects in Dart are references, similar to objects in languages like Java. When you create an instance of a class, you’re working with a reference to that instance.

Dart provides a more object-oriented approach compared to Go. In the example above, we define a Rectangle class with width and height properties, and area() and perimeter() methods.

The main() function demonstrates how to create an instance of the Rectangle class and call its methods. In Dart, you don’t need to explicitly dereference pointers or use address-of operators when working with objects and calling methods.

Next, we’ll look at Dart’s mechanism for defining interfaces, which allow for polymorphism and abstraction in object-oriented programming.