last method

T last([
  1. bool predicate(
    1. T
    )?
])

Returns the last element matching the given predicate. @throws NoSuchElementException if no such element is found.

Implementation

T last([bool Function(T)? predicate]) {
  if (predicate == null) {
    if (this is KtList) return (this as KtList<T>).last();
    final i = iterator();
    if (!i.hasNext()) {
      throw const NoSuchElementException("Collection is empty");
    }
    var last = i.next();
    while (i.hasNext()) {
      last = i.next();
    }
    return last;
  } else {
    T? last;
    var found = false;
    for (final element in iter) {
      if (predicate(element)) {
        last = element;
        found = true;
      }
    }
    if (!found) {
      throw const NoSuchElementException(
          "Collection contains no element matching the predicate.");
    }
    return last!;
  }
}