제네릭 형식의 확장 메서드

Dart 2.7부터 기존 라이브러리에 기능을 추가할 수 있습니다. 클래스에 사용하려는 메서드가 없으면 해당 메서드를 자체적으로 구현하여 해당 클래스를 확장할 수 있습니다.

업데이트하려는 라이브러리의 코드에 대해 pull 요청을 생성할 필요가 없으며 새로운 기능을 코드에 로컬로 유지할 수 있습니다. 예를 들어, Duration 형식을 지정하여 일, 시간, 분, 초를 dd:HH:MM:SS 형식으로 표시해야 하는 경우 Duration 에서 확장 메서드를 정의할 수 있습니다.

extension DurationFormatter on Duration {
  /// Returns a day, hour, minute, second string representation of this `Duration`.
  ///
  ///
  /// Returns a string with days, hours, minutes, and seconds in the
  /// following format: `dd:HH:MM:SS`. For example,
  ///
  ///   var d = new Duration(days:19, hours:22, minutes:33);
  ///    d.dayHourMinuteSecondFormatted();  // "19:22:33:00"
  String dayHourMinuteSecondFormatted() {
    this.toString();
    return [
      this.inDays,
      this.inHours.remainder(24),
      this.inMinutes.remainder(60),
      this.inSeconds.remainder(60)
    ].map((seg) {
      return seg.toString().padLeft(2, '0');
    }).join(':');
  }
}

void main() {
  var d = Duration(days:19, hours:22, minutes:33);
  print(d.dayHourMinuteSecondFormatted()); // 19:22:33:00
}


제네릭 유형에 대한 확장


Duration 와 같은 "콘크리트"유형을 확장할 수 있을 뿐만 아니라 또한 제네릭 형식의 기능을 확장하여 모든 구체적인 인스턴스(및 모든 하위 클래스)가 새 확장 메서드를 얻도록 할 수 있습니다.

예를 들어 firstWhereOrNullList 에 추가하려는 경우 목록에서 조건을 충족하는 첫 번째 요소를 반환하거나 해당 조건을 충족하는 요소가 없으면 null 다음과 같은 확장 메서드를 만들 수 있습니다. :

extension FirstWhereOrNull<E> on Iterable<E> {
  /// Returns the first element that satisfies the given predicate test.
  ///
  /// Iterates through elements and returns the first to satisfy test.
  /// If none is found, returns `null`.
  E? firstWhereOrNull(bool test(E element)) {
    for (E element in this) {
      if (test(element)) return element;
    }
    return null;
  }
}

void main() {
  final List<String> myList = ["First", "Second", "Third"];

  print(myList.firstWhereOrNull((element) => 
     element.endsWith('d'))); // Second

  print(myList.firstWhereOrNull((element) => 
     element.startsWith('d'))); // null
}


제네릭Iterable<E>에 확장 메서드를 생성하여 Queue , ListSet 과 같은 Iterable 모든 하위 클래스의 모든 구체적인 유형에 추가하고 List<E> 에도 추가합니다.

좋은 웹페이지 즐겨찾기