When lambdas and strong typing collide
I was recently working on a bit of code where I was trying to map an
HttpException thrown in an RxJava chain to a custom error type. There are a number of different ways to handle errors, so I thought about what I was looking for, then used autocomplete to search for a signature that might work.
I wanted something that took a function that takes a
Throwable in, and returns a
Flowable. Scrolling through, I found
Looking at the documentation, this was exactly what I wanted! I implemented the lambda, and for some reason it wasn’t compiling. It wasn’t recognizing the lambda input. What’s up with that?
Turns out there is a second
onErrorResumeNext function with a very similar signature:
Both of these functions take a lambda, and the compiler assumed this was the one I was going for, the one that took a lambda with no parameters.
To make this work, I had to specify the type of lambda I was passing into this function. Only then would it compile and give me the result I was looking for. Notice the
throwable: Throwable -> at the beginning of the block declaring the type of the input variable.
Strong typing can be very helpful in keeping our code safer. In situations like these, we need to be careful of watching if there are multiple functions of the same name that both take lambdas as their only parameter. You may need to specify the input type at these times!