I want to handle exceptions in a `map` lambda by s...
# functional
j
I want to handle exceptions in a
map
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?
Copy code
fun parseList(strings: Collection<String>): List<Foo>
{
    return strings.stream().map { 
        try {
            parse(it)
        } catch (e: Exception) {
            null
        }
    }.toList().filterNotNull()
}
đź‘Ť 1
s
probably just
Copy code
return strings.mapNotNull {
    try {
        parse(it)
    } catch (ignored: Exception) {
        null
    }
}
You don’t need to call
stream()
and
mapNotNull {}
will simplify the whole toList/filter bit
optimally you’d want
parse()
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 do
well, at least, as well as you can do without introducing
Try<T>
or a similar kind of data type
j
Thanks @Shawn - I had not seen the
mapNotNull
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.
e
I'd do something like this :
Copy code
val 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]