commonMain.kotlin.collections.Iterables.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-stdlib Show documentation
Show all versions of kotlin-stdlib Show documentation
Kotlin Standard Library for JVM
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections
/**
* Given an [iterator] function constructs an [Iterable] instance that returns values through the [Iterator]
* provided by that function.
* @sample samples.collections.Iterables.Building.iterable
*/
@kotlin.internal.InlineOnly
public inline fun Iterable(crossinline iterator: () -> Iterator): Iterable = object : Iterable {
override fun iterator(): Iterator = iterator()
}
/**
* A wrapper over another [Iterable] (or any other object that can produce an [Iterator]) that returns
* an indexing iterator.
*/
internal class IndexingIterable(private val iteratorFactory: () -> Iterator) : Iterable> {
override fun iterator(): Iterator> = IndexingIterator(iteratorFactory())
}
/**
* Returns the size of this iterable if it is known, or `null` otherwise.
*/
@PublishedApi
internal fun Iterable.collectionSizeOrNull(): Int? = if (this is Collection<*>) this.size else null
/**
* Returns the size of this iterable if it is known, or the specified [default] value otherwise.
*/
@PublishedApi
internal fun Iterable.collectionSizeOrDefault(default: Int): Int = if (this is Collection<*>) this.size else default
/**
* Returns a single list of all elements from all collections in the given collection.
* @sample samples.collections.Iterables.Operations.flattenIterable
*/
public fun Iterable>.flatten(): List {
val result = ArrayList()
for (element in this) {
result.addAll(element)
}
return result
}
/**
* Returns a pair of lists, where
* *first* list is built from the first values of each pair from this collection,
* *second* list is built from the second values of each pair from this collection.
* @sample samples.collections.Iterables.Operations.unzipIterable
*/
public fun Iterable>.unzip(): Pair, List> {
val expectedSize = collectionSizeOrDefault(10)
val listT = ArrayList(expectedSize)
val listR = ArrayList(expectedSize)
for (pair in this) {
listT.add(pair.first)
listR.add(pair.second)
}
return listT to listR
}