coming from Rust: what is the equivalent of a `Res...
# getting-started
y
coming from Rust: what is the equivalent of a
Result
in Kotlin, and is it idiomatic to use it? do failible functions in Kotlin generally return error types on failure, throw, or just return `null`/silently exit?
s
This is a good read regarding what is/isn’t idiomatic: https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07. However in my experience it doesn’t always represent reality, because so much Kotlin code has to interoperate with Java that people fall into the habit of using exceptions anyway.
There’s no
Result<T, E>
type in the stdlib (there is a
Result<T>
but it’s really for different things). I’d start with the
Either<E, T>
type from #arrow, but as mentioned in the linked article it’s easy enough to create your own sealed types too.
One day we’ll have proper union types 🙏
k
if you think arrow is much big, kotlin-result might be good for you
👌 1
1
y
okay, so let’s look at typical scenario here. I want to mutate the state of a class instance, but this may fail at several points for different reasons. in Kotlin you would have a single function that ends with performing the mutation, and throws an appropriate exception otherwise? which I guess you would name something like
tryDoingThing()
?
and by “in Kotlin” I mean, not my personal pet project lol in actual established codebases
k
Typically, throw exception simply.
s
For a project of any size, I’d definitely invest in a better approach that doesn’t use exceptions. There’s no compile-time type checking for exceptions in Kotlin which makes them a very low-tech and hard-to-maintain way to write program logic.
#arrow is full of better patterns for doing stuff like this, or you can always just use early returns with a sealed return type
m
I wouldn't throw an exception unless the situation was exceptional. If you expect failures due to commonly occuring reasons, don't use exceptions
y
right, because errors are typically classified into recoverable errors and errors that are unrecoverable or programmer errors
💯 1
but what would you do in the case of a recoverable error, to communicate to the user what happened?
if not exceptions then what?
m
Sealed return type of success and failure like others have mentioned. At some layer you need to translate this to a user message right?
☝️ 1
y
so basically a
Result<T, E>
yeah, the idea is that this error is bubbled up to the user which would then handle it however they choose.
k
to avoid to use exception, use arrow or define sealed result class yourself are most typically
IMO
y
okay. thanks everyone!
g
If it is not an exception, why return some kind Result which wraps expetion in this case?