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:

fun findUserByName(name: String): User throws NotFoundException, MalformedNameException

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):

val user: User = findUserByName(name)!!
val age: Int throws NotFoundException, MalformedNameException = findUserByName(name)?.age

Of course all these types would be inferred so in practice the code would not be that long:

val user = findUserByName(name)!!
val age = findUserByName(name)?.age

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:

val user = findUserByName(name).or(User("Tom"))
findUserByName(name).fold(
    { user -> println("found user $user") },
    { e -> println("exception while finding user: $e")}
  )

But for more than one exceptions it could look more and more like “extensive when” in Kotlin or “pattern matching” from Scala:

val user = findUserByName(name).or(User("Tom")) // number of exceptions doesn't matter here
findUserByName(name).fold(
    { user -> println("found user $user") },
    { notFoundException -> println("User was not found")},
    { malformedNameException -> println("Name was malformed")}
  )

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!