takeLastWhile method

  1. @useResult
KtList<T> takeLastWhile(
  1. bool predicate(
    1. T
    )
)

Returns a list containing last elements satisfying the given predicate.

Implementation

@useResult
KtList<T> takeLastWhile(bool Function(T) predicate) {
  if (isEmpty()) return emptyList();
  final iterator = listIterator(size);
  while (iterator.hasPrevious()) {
    if (!predicate(iterator.previous())) {
      iterator.next();
      final expectedSize = size - iterator.nextIndex();
      if (expectedSize == 0) return emptyList();
      final list = mutableListOf<T>();
      while (iterator.hasNext()) {
        list.add(iterator.next());
      }
      return list;
    }
  }
  return toList();
}