dave08
05/30/2024, 3:52 PMsingle()
on collections...?
fun <E, T> Raise<E>.ensureSingle(
list: List<T>,
notFound: () -> E,
multipleFound: List<T>.() -> E
): T = when {
list.size == 1 -> list.single()
list.isEmpty() -> raise(notFound())
else -> raise(list.multipleFound())
}
Kev
05/31/2024, 6:00 AMCLOVIS
05/31/2024, 7:28 AMCLOVIS
05/31/2024, 7:28 AMdave08
05/31/2024, 8:08 AMdave08
05/31/2024, 8:09 AMCLOVIS
05/31/2024, 8:10 AMdave08
05/31/2024, 8:11 AMCLOVIS
05/31/2024, 8:11 AMensureSingle
is a bit awkward to use though, because of the two lambdas 😕dave08
05/31/2024, 8:12 AMCLOVIS
05/31/2024, 8:14 AMensure(foo.isNotEmpty()) { NotFoundError() }
ensure(foo.size == 1) { TooManyItems(foo) }
val e = foo[0]
directly in my code, without creating a utility function for it.dave08
05/31/2024, 8:18 AMCLOVIS
05/31/2024, 8:24 AMcontext(Raise<CollectionIsEmpty>, Raise<CollectionHasTooManyItems>)
fun <T> ensureSingle(list: List<T>): T = when {
list.size == 1 -> list[0]
list.isEmpty() -> raise(CollectionIsEmpty)
else -> raise(CollectionHasTooManyItems(list))
}
and let the user convert the errors to their own types with recover
or withError
, but since we would be creating base error types, it should be a companion library and not within Arrow Core itselfdave08
05/31/2024, 8:29 AMdave08
05/31/2024, 8:29 AM