Skip to content

Commit

Permalink
Throw NoSuchElementException instead of UnsupportedOperationException…
Browse files Browse the repository at this point in the history
… in Flow.reduce

    * We can do it safely because reduce is still experimental
    * We will be consistent with stdlib (as soon as KT-33874 is implemented)
  • Loading branch information
qwwdfsad committed Nov 30, 2019
1 parent 391042f commit bd1687f
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions kotlinx-coroutines-core/common/src/flow/terminal/Reduce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import kotlin.jvm.*

/**
* Accumulates value starting with the first element and applying [operation] to current accumulator value and each element.
* Throws [UnsupportedOperationException] if flow was empty.
* Throws [NoSuchElementException] if flow was empty.
*/
@ExperimentalCoroutinesApi
public suspend fun <S, T : S> Flow<T>.reduce(operation: suspend (accumulator: S, value: T) -> S): S {
Expand All @@ -30,7 +30,7 @@ public suspend fun <S, T : S> Flow<T>.reduce(operation: suspend (accumulator: S,
}
}

if (accumulator === NULL) throw UnsupportedOperationException("Empty flow can't be reduced")
if (accumulator === NULL) throw NoSuchElementException("Empty flow can't be reduced")
@Suppress("UNCHECKED_CAST")
return accumulator as S
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class ReduceTest : TestBase() {
@Test
fun testEmptyReduce() = runTest {
val flow = emptyFlow<Int>()
assertFailsWith<UnsupportedOperationException> { flow.reduce { acc, value -> value + acc } }
assertFailsWith<NoSuchElementException> { flow.reduce { acc, value -> value + acc } }
}

@Test
Expand All @@ -42,7 +42,7 @@ class ReduceTest : TestBase() {
fun testReduceNulls() = runTest {
assertNull(flowOf(null).reduce { _, value -> value })
assertNull(flowOf(null, null).reduce { _, value -> value })
assertFailsWith<UnsupportedOperationException> { flowOf<Nothing?>().reduce { _, value -> value } }
assertFailsWith<NoSuchElementException> { flowOf<Nothing?>().reduce { _, value -> value } }
}

@Test
Expand Down

0 comments on commit bd1687f

Please sign in to comment.