Add Sequence.orEmpty #KT-16552 Fixed

This commit is contained in:
Toshiaki Kameyama
2018-06-15 16:25:14 +09:00
committed by Ilya Gorbunov
parent 2ce0bca34e
commit c4b785de36
3 changed files with 28 additions and 0 deletions
@@ -7,6 +7,7 @@ import kotlin.coroutines.experimental.buildSequence
@RunWith(Enclosed::class)
class Sequences {
class Building {
@Sample
@@ -158,6 +159,17 @@ class Sequences {
}
class Usage {
@Sample
fun sequenceOrEmpty() {
val nullSequence: Sequence<Int>? = null
assertPrints(nullSequence.orEmpty().toList(), "[]")
val sequence: Sequence<Int>? = sequenceOf(1, 2, 3)
assertPrints(sequence.orEmpty().toList(), "[1, 2, 3]")
}
}
class Transformations {
@@ -47,6 +47,14 @@ private object EmptySequence : Sequence<Nothing>, DropTakeSequence<Nothing> {
override fun take(n: Int) = EmptySequence
}
/**
* Returns this sequence if it's not `null` and the empty sequence otherwise.
* @sample samples.collections.Sequences.Usage.sequenceOrEmpty
*/
@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>?.orEmpty(): Sequence<T> = this ?: emptySequence()
/**
* Returns a sequence of all elements from all sequences in this sequence.
*
@@ -543,6 +543,14 @@ public class SequenceTest {
assertEquals(listOf("act", "wast", "test"), sequenceOf("act", "test", "wast").sortedWith(comparator).toList())
}
@Test fun orEmpty() {
val s1: Sequence<Int>? = null
assertEquals(emptySequence(), s1.orEmpty())
val s2: Sequence<Int>? = sequenceOf(1)
assertEquals(s2, s2.orEmpty())
}
/*
test fun pairIterator() {
val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).joinToString(limit = 10)