Ellen Spertus
05/20/2020, 10:22 PMList<String>
and a function f: String -> T?
and would like to apply f
to each element s
of the list in order until f(s)
is non-null, returning that f(s)
. If f(s)
is null for all values, null
should be returned. Here’s an ugly implementation:
fun g(list: List<String>): String? =
if (list.isEmpty()) {
null
} else {
f(list.first()) ?: g(list.subList(1, list.size))
}
Can someone suggest a more elegant way?
Here’s the code, if you’d like to play with it. https://pl.kotl.in/mByy6tkphMichael de Kaste
05/20/2020, 10:31 PMlist.firstOrNull{ f(it) != null }
Michael de Kaste
05/20/2020, 10:32 PMEllen Spertus
05/20/2020, 10:32 PMEllen Spertus
05/20/2020, 10:40 PMfirstOrNull
expects a predicate. My function f
is not a predicate.Ellen Spertus
05/20/2020, 10:41 PMlist.firstOrNull { f(it) != null }?.let { f(it) }
parth
05/20/2020, 10:43 PMlist.firstOrNull { f(it) != null }
?Ellen Spertus
05/20/2020, 10:44 PMf
.parth
05/20/2020, 10:45 PMEllen Spertus
05/20/2020, 10:46 PMparth
05/20/2020, 10:47 PMfor (s : list){
val result = f(s)
if (result == null) continue
return result
}
Ellen Spertus
05/20/2020, 10:48 PMfor( s : list){
val result = f(s)
if (result != null) {
return result
}
}
parth
05/20/2020, 10:48 PMparth
05/20/2020, 10:49 PMRuckus
05/20/2020, 10:51 PMfor (s in list) return f(s) ?: continue
(Haven't tested it, and arguably far from readable)Ellen Spertus
05/20/2020, 10:52 PMEllen Spertus
05/20/2020, 10:53 PMEllen Spertus
05/20/2020, 10:54 PMreturn null
after the for loop.araqnid
05/21/2020, 2:30 AMlist.asSequence().map(f).firstOrNull { it != null }
I think this dtrt too. tmtowtdi 🙂Michael de Kaste
05/21/2020, 10:46 AMlist.mapNotNull(::f).firstOrNull()
(sorry I went to bed)Roger Home-Martinsen
05/21/2020, 12:38 PMfun g(list: List<String>) = list.mapNotNull { str -> f(str) }.firstOrNull()
araqnid
05/21/2020, 1:54 PMRoger Home-Martinsen
05/21/2020, 3:57 PMMichael de Kaste
05/21/2020, 4:14 PMRoger Home-Martinsen
05/21/2020, 4:16 PMEllen Spertus
05/21/2020, 7:37 PMg
is a suspend function (something I didn’t mention). I ended up sticking with @Ruckus’s version. Thanks everyone! That was fun, and I learned from it.