koryphe icon indicating copy to clipboard operation
koryphe copied to clipboard

ToList produces unexpected result with arrays containing primitives

Open GCHQDeveloper314 opened this issue 1 year ago • 0 comments

The Javadoc for ToList states that it "takes an Object and converts it to a list. If the object is an array or iterable the items will be added to a new list. Otherwise a new list is created with the single value as an item". However, if an array (which is an object) containing primitives is used, the result is not as expected and is not the same as with arrays of objects.

Input ToList().apply(new int[] {1, 2}) Expected result List with values [1,2] Actual result List containing the inputted array [[1,2]]

This happens because the code for ToList only checks if the input is an array of Object, not simply if it's an array. This causes arrays of primitives to be treated the same as single objects, causing them to be wrapped inside a List. This same behaviour will be exhibited by ToSet and other similar Koryphe function classes.

An array is always an Object in Java, even if it contains primitives and not objects. To resolve this problem, either the ability to handle arrays of primitives should be added, or this type of input should be rejected and the description improved (see below).

It's worth noting that if the input is itself a primitive (e.g. ToList().apply(1)), then it will be autoboxed and converted to the equivalent object automatically. The description of "takes an Object" is not informative, as it is impossible not to pass an object to the method, because any primitives will be autoboxed to objects and an arrays of primitives is itself an object.

GCHQDeveloper314 avatar Oct 24 '22 16:10 GCHQDeveloper314