目次

メソッド

メソッドは、オブジェクトの動作を提供する関数です。

インスタンスメソッド

#

オブジェクトのインスタンスメソッドは、インスタンス変数とthisにアクセスできます。次のサンプルのdistanceTo()メソッドは、インスタンスメソッドの例です。

dart
import 'dart:math';

class Point {
  final double x;
  final double y;

  // Sets the x and y instance variables
  // before the constructor body runs.
  Point(this.x, this.y);

  double distanceTo(Point other) {
    var dx = x - other.x;
    var dy = y - other.y;
    return sqrt(dx * dx + dy * dy);
  }
}

演算子

#

ほとんどの演算子は、特別な名前を持つインスタンスメソッドです。Dartでは、次の名前で演算子を定義できます。

<><=>===~
-+/~/*%
|^&<<>>>>>
[]=[]

演算子を宣言するには、組み込み識別子であるoperatorと、定義する演算子を使用します。次の例では、ベクトルの加算(+)、減算(-)、および等価性(==)を定義しています。

dart
class Vector {
  final int x, y;

  Vector(this.x, this.y);

  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);

  @override
  bool operator ==(Object other) =>
      other is Vector && x == other.x && y == other.y;

  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  final v = Vector(2, 3);
  final w = Vector(2, 2);

  assert(v + w == Vector(4, 5));
  assert(v - w == Vector(0, 1));
}

ゲッターとセッター

#

ゲッターとセッターは、オブジェクトのプロパティへの読み取りおよび書き込みアクセスを提供する特別なメソッドです。各インスタンス変数には暗黙のゲッターがあり、適切な場合はセッターもあることを思い出してください。 getキーワードとsetキーワードを使用して、ゲッターとセッターを実装することで、追加のプロパティを作成できます。

dart
class Rectangle {
  double left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  // Define two calculated properties: right and bottom.
  double get right => left + width;
  set right(double value) => left = value - width;
  double get bottom => top + height;
  set bottom(double value) => top = value - height;
}

void main() {
  var rect = Rectangle(3, 4, 20, 15);
  assert(rect.left == 3);
  rect.right = 12;
  assert(rect.left == -8);
}

ゲッターとセッターを使用すると、インスタンス変数から始めて、後でメソッドでラップすることができます。すべてクライアントコードを変更することなく行えます。

抽象メソッド

#

インスタンスメソッド、ゲッターメソッド、セッターメソッドは抽象メソッドにすることができ、インターフェースを定義しますが、その実装は他のクラスに任せます。抽象メソッドは、抽象クラスまたはミックスインにのみ存在できます。

メソッドを抽象化するには、メソッド本体の代わりにセミコロン(;)を使用します。

dart
abstract class Doer {
  // Define instance variables and methods...

  void doSomething(); // Define an abstract method.
}

class EffectiveDoer extends Doer {
  void doSomething() {
    // Provide an implementation, so the method is not abstract here...
  }
}