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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With