I've been looking around to try to find what the reasoning is behind not including default parameters for functions in Java.
I'm aware that it's possible to simulate the behavior, either with varargs or else by creating several overloaded functions that accept fewer parameters, and call the real function that takes all parameters. However, neither of these options match the clarity and ease-of-use of, e.g. C++'s syntax.
Does anyone know if there's a solid technical reason that would make something like
void myFunc(int a=1, int b=2) {...}
undesirable or undo-able in a new version of Java?
Short answer: No. Fortunately, you can simulate them. Many programming languages like C++ or modern JavaScript have a simple option to call a function without providing values for its arguments.
Constructors cannot have default parameters.
Java allows to pass null as an argument to set default values for optional parameters! Well, specifying null to indicate that a given argument is optional might seem like the easiest option ever! You can also use @Nullable annotation, it makes it clear and simple that a method can accept null arguments!
The Python "SyntaxError: non-default argument follows default argument" occurs when we define a function with a positional parameter that follows a default parameter. To solve the error, make sure to specify all default parameters after the positional parameters of the function.
It was not in the initial version of Java because they decided they did not need it, probably to keep things simple.
Adding it now would be tricky, because it needs to be done in a backwards-compatible fashion. Adding varargs, autoboxing and generics in Java5 was a major undertaking, and it could only be done with limited functionality (such as type erasure) and at the cost of increased complexity (the new method resolution rules make for good exam trick questions).
Your best shot would be with a non-Java language on the JVM. Maybe one of them already has this.
I am not aware of a technical reason, apart from it being complicated which values are being omitted and which ones are not.
For example, in your sample, if only one integer was passed through then is it a
or b
that should be defaulted? Most probably a
but it does add that level of ambiguity.
A simple solution would be to
void myFunc(Integer a, Integer b) {
if (a == null) a = 1;
if (b == null) b = 2;
}
Yes it is more long winded, and yes it hides the defaulting within the code, rather than the method signature (which could then be shown in JavaDoc), but it does enforce the consistency.
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