identityFunction () simply returns the function itself, which will be used for different objects.
Below is an example of use:
String result = identityFunction().apply("Hello");
A type safety warning is important. This is there because IDENTITY_FUNCTION is implemented in such a way that the compiler cannot guarantee that the function returns the same type as the input. Consider the following alternative implementation:
private static UnaryFunction<Object> CONST_FUNCTION = new UnaryFunction<Object>() { public Object apply(Object arg) { return "Default"; } };
This implementation always returns a string, so it is clearly unsafe to return it as a unary function in a common data type.
In our case (IDENTITY_FUNCTION), the proof that the return type matches the input type is inside the implementation. We return the same instance, so it has the same type. When you suppress type safety warnings, it is recommended that you prove this with evidence.
Eyal schneider
source share