take method

  1. @useResult
KtList<T> take(
  1. int n
)

Returns a list containing first n elements.

Implementation

@useResult
KtList<T> take(int n) {
  if (n < 0) {
    throw ArgumentError("Requested element count $n is less than zero.");
  }
  if (n == 0) return emptyList();
  if (this is KtCollection) {
    final collection = this as KtCollection;
    if (n >= collection.size) return toList();

    if (n == 1) {
      // can't use listOf here because first() might return null
      return listFrom([first()]);
    }
  }
  var count = 0;
  final list = mutableListOf<T>();
  for (final item in iter) {
    if (count++ == n) {
      break;
    }
    list.add(item);
  }
  return KtIterableExtensions<T>(list).toList();
}