I first saw this "hardcoded" varargs in Scala e.g. https://www.scala-lang.org/api/2.12.2/scala/Tuple22.html (replace 22 to 1-21). I guess it's platform (JVM) limitation? Newer Java also has something like this, but I can't remember which class.
back
4 comments
Another example is Java's java.util.Map.of. It's a convenient method to construct a map in a single statement.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base...
This kind of function overload is present everywhere in the Java collection framework (and probably other libraries). It is a performance optimization (variadic arguments in Java require creating an array), and variadiac overloads also exist (Map.of needs a list of Map.Entry for type safety) for creating collections of any size.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base...
Do note that the created map is immutable. However, you could pass the created map to the constructor HashMap (or another type) to obtain a mutable copy of the Map created using Map.of
It doesn't have the equivalent of variadic templates, which means you can't have something like std::tuple unless you either codegen it or make it not type-safe.
I did the exact same thing in Java for an internal library in order to provide type-safe Unit, Singleton<T1>, Pair<T1, T2>, etc.
I don't think I have seen classes with many parameters to avoid varargs in Java, however I have certainly seen classes with dozens of Type Parameters, I believe some form of code generation was responsible.
Can't for the life of me find that class again.
SLF4J Loggers define up to two arguments for precisely this purpose:
https://www.slf4j.org/apidocs/org/slf4j/Logger.html#error(ja......)
> This form avoids superfluous string concatenation when the logger is disabled for the ERROR level. However, this variant incurs the hidden (and relatively small) cost of creating an Object[] before invoking the method, even if this logger is disabled for ERROR. The variants taking one and two arguments exist solely in order to avoid this hidden cost.
Look at Set.of and Map.of. Lots of overloads to avoid allocating the vararg array.
It’s to prevent allocating the array for varargs.
Yes. This used to be one of those things that made a significant difference but probably doesn't matter any more. I say "probably" because I haven't seen any code like this that wasn't spat out from a generator in a long time