kotlin.Result is half-baked and is likely to change in the future.
A little bit of history -
kotlin.Result was introduced in 1.3 as an internal class first, as it was intended to be used by compiler generated code only - namely coroutines. However, it was during testing process made public, since programmers saw the usefulness of the class as a Try monad and some of our users, particularly, arrow project, wanted to replace their own implementations of Try monad with the standard one.
Despite being forbidden by default, return
kotlin.Result from a function is fully supported in the compiler and we try not to break the code, which returns
The reasons why it is forbidden by default are two-fold.
First, we might want to treat
kotlin.Result similar to nullable types. I.e. possibly add a new syntax, for instance, ceylonesque
T | IllegalStateException. Additionally, we might want to extend
?: to support that kind of types. Similar to nullables,
?. is to retrieve value, and part after
?: is executed if there is an exception, wrapped in the result.
Second, Kotlin does not support checked exceptions of any kind. However, some exceptions, like
FileNotFoundException are checked in Java for a reason, and not catching the exception is an error. Returning result class enforces a user to check the value. So, it can be viewed as a replacement for checked exception. In that case, it is logical to compile functions, returning
kotlin.Result as functions, returning value type and throwing the exception, so, when the user calls the function from Java, it is seen as a function, throwing checked exception, and thus, the user has to catch it.
Because of these two design issues, we do not encourage use of
kotlin.Result as a return type - because sometime in the future there can be a breaking change of some kind. However, since we see the need for checked exceptions and Try monad, we do support it.