Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there any function like ObjectUtils#defaultIfNull ? #388

Open
kerraway opened this issue Oct 27, 2023 · 2 comments
Open

Is there any function like ObjectUtils#defaultIfNull ? #388

kerraway opened this issue Oct 27, 2023 · 2 comments

Comments

@kerraway
Copy link

kerraway commented Oct 27, 2023

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.

@ivila
Copy link

ivila commented Oct 31, 2023

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.

@kerraway
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants