Is there any function like ObjectUtils#defaultIfNull ?
When I write validation codes, I want to write something like:
result, err := process(args)
if err != nil || result < 0 {
notNilErr := lo.DefaultIfNil(err, errors.New("result must not less than 0."))
return errors.Wrapf(err, "process failed, args: %v", args)
}
lo.DefaultIfNil is from my imagination, it was inspired by the org.apache.commons.lang3.ObjectUtils#defaultIfNull method, lol.
Could lo lib offer something like lo.DefaultIfNil? And I think lo.DefaultIfEmpty is another good function for handling string, slice and map. I'd like to make a MR for adding those functions if the proposal is accepted.
If there are some functions supporting my requirement already, plz let me known. THX.
Actually, I am surprised by a common package have this function as Java support conditional operator. In Java we can achieve it by using conditional operator:
int a = b ? c : d;
I think we could just add a conditional operator like function, it could suit more cases, for example, the if function
func If[T](b bool, v1, v2 T) T {
if b {
return v1
}
return v2
}
And you can use it like
lo.If(err != nil, err, errors.New("result must not less than 0."))
But on my opinion, we should not add either of these functions, as adding too many functions will result in confusing, making users busy in finding suitable functions. I am a Java user too, I know that Java have an Optional class to handle situation like this(Null situation), I am really tired by those.
Thx @ivila, I got your opinion, but you misused the function, you should use func Ternary[T any](condition bool, ifOutput T, elseOutput T) T instead of func If[T any](condition bool, result T) *ifElse[T]. As we all know, golang can't support overloading method.