Why can’t ‘kotlin.Result’ be used as a return type?

From the Kotlin KEEP:

The rationale behind these limitations is that future versions of
Kotlin may expand and/or change semantics of functions that return
Result type and null-safety operators may change their semantics when
used on values of Result type. In order to avoid breaking existing
code in the future releases of Kotin and leave door open for those
changes, the corresponding uses produce an error now. Exceptions to
this rule are made for carefully-reviewed declarations in the standard
library that are part of the Result type API itself.

Note: if you just want to experiment with the Result type you can bypass this limitation by supplying a Kotlin compiler argument -Xallow-result-return-type.

When using Gradle on Java or Android project:
Define the compiler argument on Kotlin compilation task. It applies both for production code and tests.

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
    }
}

When using Gradle on Multiplatform project:
Define the compiler argument for each target compilation. It applies both for production code and tests.

kotlin {
    targets.all {
        compilations.all {
            kotlinOptions {
                freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
            }
        }
    }
}

Leave a Comment