Enabling Kotlin 1.3's Support for Returning Result in Standard Library

Kotlin 1.3 was released recently. There’s a number of interesting changes. Coroutines have graduated from experimental, contracts, and inline classes have been useful in my own work so far. You can read about the changes on the Kotlin website

There’s another feature I find very useful: the new Result type.

I first used the Result Monad in Rust. I don’t write much Rust anymore, but I definitely appreciate the patterns that came from functional programming. With the Result type in Kotlin I can continue to use this to my advantage.

Instead of throwing Exceptions or allowing a null, we can use the Result type to capture the Exception and return a nicely typed object. We can avoid NPEs by using Result, and we get the benefits of static typing when we try to use the object. We can then transform the Result to a new Result using Result.map or Result.fold. We could also perform actions with side effects by using Result.onSuccess. The flexibility is nice and having type safety is a huge win.

One of the limits of the Result at the moment is that you can’t use it practically without enabling a flag. If you try, you’ll get an error like this:

kotlin.Result' cannot be used as a return type

Sad face. Unfortunately there’s not much documentation around how to use this, other than an answer on Stack Overflow.

If you’re using Maven, you can add a compiler flag argument under the configuration:


If you’re using gradle:

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
    kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
    kotlinOptions.freeCompilerArgs = ["-Xallow-result-return-type"]

You should be able to use the Result monad using Kotlin 1.3. A word of warning though: it’s disabled by default because it may change in future versions.

If you found this post helpful, please consider sharing to your network. I'm also available to help you be successful with your distributed systems! Please reach out if you're interested in working with me, and I'll be happy to schedule a free one-hour consultation.