Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Function with primitive return or argument type in Java?

In Java 8, there is a feature akin to a function-pointer(java.util.function.Function). It is usually used like this: Function<LookupKey,LookupResult>, however, there is a problem if the method returns a primitive type. Function<ArgType,Void.TYPE> doesn't work, it fails to compile with a very confusing error message("cannot find symbol Void.TYPE"). I would rather avoid changing my method to return an Object just to pass null as the result.

like image 299
user69874 Avatar asked Sep 15 '25 04:09

user69874


1 Answers

If your function should not return a value, consider using Consumer<T> instead.

If your function should return an ìnt or long consider using ToIntFunction<T> or ToLongFunction<T> which returns primitive types.

If your function should return boolean, then use Predicate<T>.

And finally, if you need to consume an primitive type but want to return a reference type use IntFunction<T> or LongFunction<T>.

To complete the list: IntToLongFunction, LongToIntFunction, IntUnaryOperator and LongUnaryOperator support primitive types to be consumed and returned.

like image 192
Harmlezz Avatar answered Sep 17 '25 02:09

Harmlezz