Skip to content

Commit bd1687f

Browse files
committed
Throw NoSuchElementException instead of UnsupportedOperationException 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)
1 parent 391042f commit bd1687f

File tree

2 files changed

+4
-4
lines changed

2 files changed

+4
-4
lines changed

kotlinx-coroutines-core/common/src/flow/terminal/Reduce.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import kotlin.jvm.*
1515

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

33-
if (accumulator === NULL) throw UnsupportedOperationException("Empty flow can't be reduced")
33+
if (accumulator === NULL) throw NoSuchElementException("Empty flow can't be reduced")
3434
@Suppress("UNCHECKED_CAST")
3535
return accumulator as S
3636
}

kotlinx-coroutines-core/common/test/flow/terminal/ReduceTest.kt

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class ReduceTest : TestBase() {
2323
@Test
2424
fun testEmptyReduce() = runTest {
2525
val flow = emptyFlow<Int>()
26-
assertFailsWith<UnsupportedOperationException> { flow.reduce { acc, value -> value + acc } }
26+
assertFailsWith<NoSuchElementException> { flow.reduce { acc, value -> value + acc } }
2727
}
2828

2929
@Test
@@ -42,7 +42,7 @@ class ReduceTest : TestBase() {
4242
fun testReduceNulls() = runTest {
4343
assertNull(flowOf(null).reduce { _, value -> value })
4444
assertNull(flowOf(null, null).reduce { _, value -> value })
45-
assertFailsWith<UnsupportedOperationException> { flowOf<Nothing?>().reduce { _, value -> value } }
45+
assertFailsWith<NoSuchElementException> { flowOf<Nothing?>().reduce { _, value -> value } }
4646
}
4747

4848
@Test

0 commit comments

Comments
 (0)