Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Random::nextInt not allowed in java as method reference?

Tags:

java

java-8

So I was reading generics and functional interfaces. There were two ways shown - Using Lambdas, Using method references. There were below examples used:

Predicate<String> ref = String::isEmpty;

Java uses the parameter supplied at runtime as the instance on which isEmpty is called. This is allowed because isEmpty() is an instance method in String class and doesn't take any parameter.

My question is, why does it shows compile error when I use the below line of code:

Supplier<Integer> ref2 = Random::nextInt;

After all, nextInt() is an instance method in Random class just like isEmpty() in String class and it doesn't take parameter either.

like image 686
Bharadwaj Joshi Avatar asked May 07 '26 02:05

Bharadwaj Joshi


1 Answers

Random::nextInt is an instance method, so it needs an instance of Random in order to be called. Just like you can't call String::isEmpty without a String. That's why String::isEmpty is a match for Predicate<String>: it takes a String as an argument and returns a boolean.

Similarly, Random::nextInt needs an instance of Random as an argument, and returns an int. So it could be used as a Function<Random, Integer>; but not a Supplier<Integer>, because it cannot be called without arguments.

Alternatively, if you have an instance of Random, you can use a reference to the nextInt method of that particular instance as a Supplier.

Random random = new Random();
Supplier<Integer> randomIntSupplier = random::nextInt;
like image 157
khelwood Avatar answered May 08 '26 15:05

khelwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!