I came across some Java code that had the following structure:
public MyParameterizedFunction(String param1, int param2)
{
this(param1, param2, false);
}
public MyParameterizedFunction(String param1, int param2, boolean param3)
{
//use all three parameters here
}
I know that in C++ I can assign a parameter a default value. For example:
void MyParameterizedFunction(String param1, int param2, bool param3=false);
Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?
No. In general Java doesn't have much (any) syntactic sugar, since they tried to make a simple language.
No.
You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.
As Scala was mentioned, Kotlin is also worth mentioning. In Kotlin function parameters can have default values as well and they can even refer to other parameters:
Like Scala, Kotlin runs on the JVM and can be easily integrated into existing Java projects.
Sadly, no.
I might be stating the obvious here but why not simply implement the "default" parameter yourself?
for the default you would ether use
func("my string");
and if you wouldn't like to use the default, you would use
func("my string", false);
It is not supported but there are several options like using parameter object pattern with some syntax sugar:
In this sample we construct
ParameterObject
with default values and override them in class instance initialization section{ param1 = 10; param2 = "bar";}