Add samples for Iterables #KT-20357

This commit is contained in:
kenji tomita
2017-10-23 23:09:59 +09:00
committed by Ilya Gorbunov
parent 5da1b4c566
commit 75348dd0c0
2 changed files with 46 additions and 0 deletions
@@ -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])")
}
}
@@ -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 <T> Iterable(crossinline iterator: () -> Iterator<T>): Iterable<T> = object : Iterable<T> {
@@ -73,6 +74,7 @@ internal fun <T> Iterable<T>.convertToSetForSetOperation(): Collection<T> =
/**
* Returns a single list of all elements from all collections in the given collection.
* @sample samples.collections.Iterables.flattenIterable
*/
public fun <T> Iterable<Iterable<T>>.flatten(): List<T> {
val result = ArrayList<T>()
@@ -86,6 +88,7 @@ public fun <T> Iterable<Iterable<T>>.flatten(): List<T> {
* 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 <T, R> Iterable<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
val expectedSize = collectionSizeOrDefault(10)