clueless coding // TODO: be smarter


Default and Optional Parameters in Java

Default Parameters

Default parameters in many languages are a welcome feature - for those who don’t know, default parameters allow users of a function to optionally pass in a parameter. If the function does not receive a variable, it will use its default value instead. For example:

int foo(int a, int b = 10) {
  return a + b;
}

foo(1); // returns 11
foo(1, 1); // returns 2

Simple and useful, right?



Using Default Parameters in Java

Unfortunately, that syntax is unavailable in Java, despite being common in languages such as C++ and C#.

What we can do, though, is make us of varargs. They’re arguably less clean, and have quite a bit of overhead compared to the above param = default syntax above. Regardless, if you find yourself repeating functions over and over just to implement some optional/default parameters, they might be useful.

This approach essentially translates something like Boolean... into an array of your default parameters, and only allows default parameters to be placed at the end of a function signature.

For a function where b is a default parameter…

int foo(int a, bool b = false) {}

we can translate it to Java like so:

void foo (Integer a, Boolean... defaults) {
  Boolean b = false; // DEFAULT VALUE
  if (defaults.length > 0) {
    b = defaults[0];
  }
}

or, in more concise syntax

void foo (Integer a, Boolean... defaults) {
  Boolean b = defaults.length > 0 ? defaults[0] : false;
}

The above examples have the paramter b default to false.

If we want multiple default paramters, we follow the same approach:

For a function where b AND c are default parameters

int foo(int a, bool b = false, int c = 10) {}

we can translate it to Java like so:

void foo (Integer a, Boolean... defaults) {
  Boolean b = defaults.length > 0 ? (Boolean)defaults[0] : false;
  Integer c = defaults.length > 1 ? (Integer)defaults[1] : 10;
}