https://kotlinlang.org logo
#library-development
Title
# library-development
a

Alex Ch

07/13/2020, 4:49 PM
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

Zach Klippenstein (he/him) [MOD]

07/13/2020, 4:57 PM
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

Alex Ch

07/13/2020, 5:01 PM
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

Zach Klippenstein (he/him) [MOD]

07/13/2020, 5:03 PM
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

Alex Ch

07/13/2020, 5:05 PM
Another option was to use
Either<L,R>
3 Views