diff --git a/libraries/stdlib/samples/test/samples/collections/iterables.kt b/libraries/stdlib/samples/test/samples/collections/iterables.kt new file mode 100644 index 00000000000..f6d00c5148b --- /dev/null +++ b/libraries/stdlib/samples/test/samples/collections/iterables.kt @@ -0,0 +1,43 @@ +/* + * Copyright 2010-2017 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package samples.collections + +import samples.* +import kotlin.coroutines.experimental.buildIterator +import kotlin.test.* + +class Iterables { + + @Sample + fun iterable() { + val iterable = Iterable { buildIterator { yieldAll(1..3) } } + val result = iterable.mapIndexed { index, i -> index + i } + assertPrints(result, "[1, 3, 5]") + } + + @Sample + fun flattenIterable() { + val deepList = listOf(listOf(1), listOf(2, 3), listOf(4, 5, 6)) + assertPrints(deepList.flatten(), "[1, 2, 3, 4, 5, 6]") + } + + @Sample + fun unzipIterable() { + val list = listOf(1 to 'a', 2 to 'b', 3 to 'c') + assertPrints(list.unzip(), "([1, 2, 3], [a, b, c])") + } +} \ No newline at end of file diff --git a/libraries/stdlib/src/kotlin/collections/Iterables.kt b/libraries/stdlib/src/kotlin/collections/Iterables.kt index 1d6106baa54..3c6f59cf32e 100644 --- a/libraries/stdlib/src/kotlin/collections/Iterables.kt +++ b/libraries/stdlib/src/kotlin/collections/Iterables.kt @@ -20,6 +20,7 @@ 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.iterable */ @kotlin.internal.InlineOnly public inline fun Iterable(crossinline iterator: () -> Iterator): Iterable = object : Iterable { @@ -73,6 +74,7 @@ internal fun Iterable.convertToSetForSetOperation(): Collection = /** * Returns a single list of all elements from all collections in the given collection. + * @sample samples.collections.Iterables.flattenIterable */ public fun Iterable>.flatten(): List { val result = ArrayList() @@ -86,6 +88,7 @@ public fun Iterable>.flatten(): List { * 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.unzipIterable */ public fun Iterable>.unzip(): Pair, List> { val expectedSize = collectionSizeOrDefault(10)