So the release of Kotlin 1.5 finally unlocks the u...
# announcements
c
So the release of Kotlin 1.5 finally unlocks the use of
Result
by default! I was surprised to find this out given how quiet this change was. Using
Result
as a return type for libraries and in general seems like a great middle ground between the looseness of unchecked exceptions and the verboseness of sealed classes as return types. You can force callers of your method to handle any failure by simply doing
fun method(): Result<T> = runCatching { ... }
, allowing uncaught exceptions in the method to bubble up into the failure case of the result. This is much less code than creating a sealed class for every failure case and writing the logic to convert each exception to them. Easier to read and reason about, and doesn't even force you to adopt functional-style-programming. Now that this is doable with vanilla Kotlin, what does everyone think? Would you adopt this as your default way of error handling? How would you feel consuming a library that exclusively used
Result
instead of throwing exceptions?
j
I miss the loading state. Result only offers success or error, but I often want to know if things are being loaded as well
h
Depends on the lib and the kind of exceptions whether i would prefer that tbh. When the exceptions are proper results that make sense to be handled locally than i would prefer sealed classes or kotlin-result results. Kotlins result lacks generic failure type, which would mean you never know WHAT specific failure you get. When thats okay for the domain... Hmmm... Yes than Result would be good i guess.
c
I suppose for the loading state, you could still return a result of a sealed class type or enum type. I view this is as best compared to unchecked exceptions, since many people don't bother with writing sealed classes for return types. Low-effort is an overlooked trait.
j
Well I have my own sealed result class for a while with Success, Error and Loading. It fits my needs perfectly, especially because of the lack of checked exceptions in kotlin it is very unwise to throw errors (in a frontend application) and result.error class is a very very nice way of handling things in my opinion.
I'm always surprised how many ways there are built into kotlin to catch errors, also in flows, as you shouldn't throw errors if you don't want your program to actually terminate (so why catch them?)