메서드

메서드 (Methods)

메서드는 객체에 동작(behavior)을 제공하는 함수예요. Dart에서 메서드가 어떻게 선언되고 사용되는지, 인스턴스 메서드부터 연산자, getter/setter, 추상 메서드까지 하나씩 살펴볼게요.

출처: Dart 공식 문서 - Methods

본문

인스턴스 메서드 (Instance methods)

객체의 인스턴스 메서드는 인스턴스 변수와 this에 접근할 수 있어요. 다음 예시의 distanceTo()가 인스턴스 메서드의 한 예시예요.

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);
  }

}

연산자 (Operators)

대부분의 연산자는 특별한 이름을 가진 인스턴스 메서드예요. Dart는 다음 이름으로 연산자를 정의할 수 있게 해줘요.

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

연산자를 선언하려면 내장 식별자 operator를 쓰고 그 뒤에 정의할 연산자를 적으면 돼요. 다음 예시는 벡터 덧셈(+), 뺄셈(-), 동등성(==)을 정의해요.

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));
}

Getter와 Setter

Getter와 setter는 객체의 프로퍼티에 대한 읽기와 쓰기 접근을 제공하는 특별한 메서드예요. 각 인스턴스 변수에는 암시적 getter가 있고, 적절하다면 setter도 있어요. 여기에 더해 getset 키워드를 사용해 getter와 setter를 구현함으로써 추가적인 프로퍼티를 만들 수도 있어요.

/// A rectangle in a screen coordinate system,
/// where the origin `(0, 0)` is in the top-left corner.
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);
}

getter와 setter를 쓰면 인스턴스 변수로 시작해 나중에 그 변수들을 메서드로 감쌀 수 있어요. 클라이언트 코드는 전혀 바꿀 필요가 없죠.

추상 메서드 (Abstract methods)

인스턴스 메서드, getter, setter 메서드는 **추상(abstract)**일 수 있어요. 즉 인터페이스를 정의하되, 그 구현은 다른 클래스에 맡기는 거죠. 추상 메서드는 오직 추상 클래스나 믹스인 안에서만 존재할 수 있어요.

메서드를 추상으로 만들려면 메서드 본문 대신 **세미콜론(;)**을 쓰면 돼요.

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...
  }
}

더 알아보기 (Learn more)

  • Dart 공식 문서 - Methods 원문 살펴보기
  • 연산자 오버로딩, getter/setter 그리고 추상 멤버에 대한 더 자세한 내용은 클래스와 타입 시스템 문서에서 함께 볼 수 있어요.