If you want to read something that will be applicable in the real world right away - this post has no use for you. But if you want to see what future of error/exception handling in Kotlin might look like - grab your crystal ball and join me!
These are POSSIBLE future improvements. Definitely interesting, but still - its only speculation.
In “Integration into the language” section of SuccessOrFailure (now changed to “Result”) class proposal Roman Elizarov writes about very interesting idea for future improvement. Assume we have function with signature:
Here Roman Elizarov speculates that compiler could treat whole User throws NotFoundException, MalformedNameException
as function return type. This type would represent “User or NotFoundException or MalfromedNameException” so something like Either<User, NotFoundException, MalfromedNameException>
.
Contrary to usual exception in Kotlin, it would force consumer to take into account that there might be exception. Similarly how nullable types force consumer to take into account that value might be null and handle such case.
Going further, such type would behave similar to nullable type in reference to operators ?.
, ?:
, and !!
so it could be used like this (my interpretation):
Of course all these types would be inferred so in practice the code would not be that long:
Let our imagination run wild and think how compiler might enforce handling all exceptions when value must be actually used. One exception is easy, as it’s similar to Try/Either:
But for more than one exceptions it could look more and more like “extensive when” in Kotlin or “pattern matching” from Scala:
KEEP also states that it can be implemented efficiently, avoiding cost of boxing and unboxing, which is even more awesome.
As for Java interoperability, it’s simple - these types with exception might be translated to checked exceptions for Java side. So Java integration would be a non-issue.
This whole idea is very interesting approach to middle ground between Java and functional exception handling. Ok, middle ground more inclined towards functional handling.
Is it the best way? I have no idea. Do I want to give it a try? Hell yeah!