javaru
12/02/2019, 7:47 PMmap
lambda by simply not mapping a value for when the exception happens? I"m currently adding null
to the stream, then filtering out the nulls at the end. Is this the best and most idomatic way to handle this case?
fun parseList(strings: Collection<String>): List<Foo>
{
return strings.stream().map {
try {
parse(it)
} catch (e: Exception) {
null
}
}.toList().filterNotNull()
}
Shawn
12/02/2019, 7:55 PMreturn strings.mapNotNull {
try {
parse(it)
} catch (ignored: Exception) {
null
}
}
You don’t need to call stream()
and mapNotNull {}
will simplify the whole toList/filter bitShawn
12/02/2019, 7:56 PMparse()
to return R?
to get rid of the need to try/catch at this call site but if you don’t own it I think this is about as well as you can doShawn
12/02/2019, 8:00 PMTry<T>
or a similar kind of data typejavaru
12/02/2019, 8:16 PMmapNotNull
function. That seems better. (I'm still getting a handle on Functional programming after 25 years in OOP land)
And yeah, I don't own the parse
method, so I need to deal with the exception.enhan
12/03/2019, 10:10 AMval l = listOf("1", "e", "42")
l.flatMap { s -> try {
listOf(Integer.decode(s))
} catch(e: Exception){
emptyList<Int>()
}
}
// Output : kotlin.collections.List<kotlin.Int> = [1, 42]