https://kotlinlang.org logo
#functional
Title
# functional
j

javaru

12/02/2019, 7:47 PM
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

Shawn

12/02/2019, 7:55 PM
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

javaru

12/02/2019, 8:16 PM
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

enhan

12/03/2019, 10:10 AM
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]
24 Views