Alex Ch
07/13/2020, 4:49 PMfun 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:
library.authenticate(::onAuthenticationResult);
private Unit onAuthenticationResultReady(AuthenticationResult authenticationResult) {
// DO something with authenticationResult
return Unit.INSTANCE;
}
Thank you.Zach Klippenstein (he/him) [MOD]
07/13/2020, 4:57 PM1. 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.Alex Ch
07/13/2020, 5:01 PMYes, this is idiomatic in Kotlin and more type safe than throwing exceptions.Is there any resource I can read more about it?
Zach Klippenstein (he/him) [MOD]
07/13/2020, 5:03 PMZach Klippenstein (he/him) [MOD]
07/13/2020, 5:04 PMZach Klippenstein (he/him) [MOD]
07/13/2020, 5:04 PMAlex Ch
07/13/2020, 5:05 PMEither<L,R>