Today I’ll comment on a commonly overlooked feature now available in Java (since Java 5.0) called “varargs”.
How many times have you done this?
public ConstructorOne(String personFullName){
// Does something
}
//and later on added another constructor that took another parameter
public ConstructorOne(String personFirstName, String personLastName){
// Now breaks down the name to pass along two strings instead of one.
}
// and so on...
Well, not anymore. You now have a new arsenal in your toolkit. In comes, “varargs” - stands for variable arguments.
You can rewrite that as this.
public constructorOne(String... parts){
if (parts.length == 2){
//process personFirstName, personLastName here
} else{
//process personFullName logic here }
}
Although this functionality exists in Scala (called Tuples) and does a better job - even while returning data of multiple types. This is a good start for Java.
Now the next question one would ask is - what happens when you want to pass a list of arguments of different types. Well here’s the solution:
public constructorOne(Object... parts){
//your logic here
}
Cheers.
