I'm trying to use kotlin `Result` in my K/Mpp proj...
# multiplatform
j
I'm trying to use kotlin
Result
in my K/Mpp project and I'm facing a lot of
Result cannot be used as a return type
warnings.
freeCompilerArgs = ["-Xallow-result-return-type"]
makes it so it can compile just fine, but the warnings are still there which is pretty annoying. Am I missing some other flag which would me allow to get rid of these IDE warnings?
r
Are you sure you want to use this type? There is a warning for a reason
g
Nope, unfortunately there is no flag to disable warning for unsafe compiler features
👍 1
j
Thank you Andrey. @ribesg I would like to just try it out, nothing too serious, but these warnings were annoying
🆗 1
d
Do you really need to use it as a return type?
j
What's the alternative? Unpack and return value/throw error in every method?
d
Yeah, pretty much I guess. What's wrong with good old throw?
j
That's true, I agree that this warning could be worked around as such. But just for discussion, unpacking Result kind breaks kotlin's semi-functional flow, I would much rather like to use chains of map/run than upack & throw
d
Yeah but instead of returning Result, I think it should be up to the caller to do
runCatching
and then do functional stuff when it wants to. Kotlin is still an imperative language although it has some functional features.
Result IMHO is meant for async code. Where it has to be functional.
g
Where it has to be functional
Async code not necessary functional
but I agree, if you have some feature-like async abstraction (functional as Rx, or simple imperative callback), you don’t need Result
But for coroutines and suspend functions Result may have much more sense
I tried, but found that tho result improves safety, it make code much less readable if you have multiple functions with Result. it looks much cleaner wrap to try/catch block with all those suspend function calls (how with any other imperative code)
j
And what about performance? Don't multiple try/catch statements impact how much can compiler optimize code?
d
If we're still talking about the JVM here. There's no real difference.
Both code styles will require creating the expensive exception anyway.
Also I haven't thought about this too much but I feel
Result
and coroutine cancellation may not play nice together.
g
try/catch is not slower in any case, it doesn't create objects, it's bytecode instruction. Exception creation (but not throwing) is relatively heavy, no need to do this in some hot part of code , but you have exactly the same for Result + wrapper object (for exception)