getOrNull
Globegitter opened this issue Β· comments
Hey, it would be nice if I could do result.getOrNull
or result.getOrElse(null)
or similar as sometimes nulls are used to show there is an error instead of an exception being thrown.
I think we already have getOrElse
but not getOrNull
, however I am not so sure about result.getOrElse(null)
though.
Do you think just getOrNull
would be enough for your usecase?
@kittinunf I would think probably getOrNull
, because I suppose otherwise it could be confusing with the return types, as in one case we would want to return a nullable type and in the other not.
Just running into another case, where I want to use getOrElse
but I want to use some information of the error-class to construct the class in the else part, so it would be nice to have something like:
inline infix fun <V: Any, E: Exception> Result<V, E>.getOrElse(transform: (E) -> V): V {
return when (this) {
is Result.Success -> value
is Result.Failure -> transform(error)
}
}
In my opinion this could even replace the existing getOrElse
as this would cover all cases, but it would of course be a breaking change, which might not be so ideal. Either way though, what do you think about the idea?
And getOrNull
would be something like:
fun <V: Any, E: Exception> Result<V, E>.getOrNull(): V? {
return when (this) {
is Result.Success -> value
is Result.Failure -> null
}
}
I am also happy to send out a PR for this if we can agree on the naming, etc.
Looks awesome! Please send PR! I will take a look at it πͺπ
Thanks for discussion and helpful suggestion.
@kittinunf any chance you can look at the pull requests I opened, would love to be able to use them in our code-base from an officially released version π
Sure sure! I have commented on it! Sorry for being late π
Do you think we should quickly bump new version for #62 so you can use right away in your project?
Shall we close this? π
Yep can be closed. Thanks for working together in this :)