Wrapper for kotlin.Result
with KMM goodness, s.t. it becomes possible to expose a result class to
public APIs interfacing with platform-specific code. For Kotlin/Native (read: iOS), this requires a Result
equivalent, which
is not a value class (a sealed Either
type also does not interop well with Swift).
KmmResult
comes to the rescue! →Full documentation.
This library is available at maven central.
dependencies {
api("at.asitplus:kmmresult:$version") //This library was designed to play well with multiplatform APIs
} //and is therefore intended to be exposed through your public API
Creation of Success
and Failure
objects is provided through a companion:
var intResult = KmmResult.success(3)
intResult = KmmResult.failure (NotImplementedError("Not Implemented"))
Also provides map()
to transform success types while passing through errors and mapFailure
to transform error types
while passing through success cases.
In addition, the more generic fold()
is available for conveniently operating on both success and failure branches.
There really is not much more to say, except for two things:
KmmResult
sportsunwrap()
to conveniently map it to thekotlin.Result
equivalent- It provides a
Result.wrap()
extension function to go the opposite way.
Refer to the full documentation for more info.
Works from the JVM as expected:
KmmResult<Boolean> demonstrate() {
if (new Random().nextBoolean())
return KmmResult.failure(new NotImplementedError("Not Implemented"));
else
return KmmResult.success(true);
}
Use the initializers:
func funWithKotlin() -> KmmResult<NSString> {
if 2 != 3 {
return KmmResult(failure: KotlinThrowable(message: "error!"))
} else {
return KmmResult(value: "works!")
}
}
Happy folding!