Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java is there a syntax for specifying zero or one value passed to method?

So I found that we have the 3 dot notation for zero or more but is there anything for zero or one?

I'm needing to alter a method and rather than overloading it I was wondering if there is a syntax to just allow for zero or one value passed?

public void test(String sample, ObjectMapper... argOm){
    ObjectMapper om = (!argOm.equals(null)?argOm:new ObjectMapper());
}

This does not do what I want as it is expecting [ ]. I just want to zero or one.

Is overloading the only way aside from altering all references to this?

like image 238
Elijah Avatar asked Dec 07 '22 19:12

Elijah


1 Answers

If you would like the compiler to check the number of arguments for you, you need to use overloading. Unfortunately, Java does not offer the default parameter mechanism, which is used for modeling "zero or one" in other languages.

Fortunately, the overload is very simple, and it lets you replace the conditional assignment in your implementation:

public void test(String sample){
    test(sample, new ObjectMapper());
}
public void test(String sample, ObjectMapper om){
    if (om == null) {
        throw new IllegalArgumentException("object mapper");
    }
    ...
}

Note that your conditional code that used to allow callers pass no object mapper is replaced with the overload, which detects this situation at compile time.

like image 113
Sergey Kalinichenko Avatar answered Apr 15 '23 03:04

Sergey Kalinichenko