Is there a more idiomatic way than aborting a loop...
# codingconventions
m
Is there a more idiomatic way than aborting a loop if needed and returning
null
if it completes?
Copy code
interface Foo
interface FooProvider { fun provide(): Foo? }

fun provideFoo(providers: List<FooProvider>): Foo? {
	for (provider in providers)
		provider.provide()?.let { return it }

	return null
}
I miss something like
providers.firstNonNullMapped { it.provide() }
(and with a better name).
a
providers.asSequence().mapNotNull(FooProvider::provide).firstOrNull()
?
m
That’s one way, yes 🤔 Just a little long and with multiple intermediary objects created.
s
it’s like three chained method calls, and the sequence operations are optimized pretty well by the compiler
☝️ 1
I wouldn’t stress about it.
m
Exactly, also if you don’t like the verbosity of that expression or you need to use it in many places, just encapsulate it in an extension function
t
that's what I did in a current project. I just wrote my own
mapFirstNotNull
extension method that does the returning loop
m
asSequence
avoids creating intermediary collections IIRC.