Prerequisites: I have an library API method and r...
# library-development
a
Prerequisites: I have an library API method and return type:
Copy code
fun authenticate(callback: (AuthenticationResult) -> Unit) {
        // authenticate
        // callback(result)
    }

    sealed class AuthenticationResult {

        object Success : AuthenticationResult()

        object Failed : AuthenticationResult()

        data class Error(val reason: String) : AuthenticationResult()

        object NetworkError : AuthenticationResult()
    }
Questions: 1. Is this a good way to provide result as errors and non-errors in the same Result object? (nothing is being thrown) 2. Is there a better way to use it in Java than:
Copy code
library.authenticate(::onAuthenticationResult);

private Unit onAuthenticationResultReady(AuthenticationResult authenticationResult) {
    // DO something with authenticationResult
    return Unit.INSTANCE;
}
Thank you.
z
1. Is this a good way to provide result as errors and non-errors in the same Result object? (nothing is being thrown)
Yes, this is idiomatic in Kotlin and more type safe than throwing exceptions.
2. Is there a better way to use it in Java than:
You could make an interface for your callback instead of using a raw function type, allows Java callers to pass lambdas. Starting in Kotlin 1.4, you can declare it as a
fun interface
, which means Kotlin callers can also pass lambdas. Until then, you can make an overload that accepts a Kotlin function type and creates an anonymous instance of the interface.
a
Thank you.
Yes, this is idiomatic in Kotlin and more type safe than throwing exceptions.
Is there any resource I can read more about it?
z
I don’t know of any general resources. But the coroutines library uses it internally, it’s used extensively in the codebase I work in, and i’ve seen it all over.
Network errors aren’t actually “exceptional”.
a
Another option was to use
Either<L,R>