Sto giocando con Java 8 per scoprire come funziona come cittadini di prima classe. Ho il seguente frammento:
package test;
import java.util.*;
import java.util.function.*;
public class Test {
public static void myForEach(List<Integer> list, Function<Integer, Void> myFunction) {
list.forEach(functionToBlock(myFunction));
}
public static void displayInt(Integer i) {
System.out.println(i);
}
public static void main(String[] args) {
List<Integer> theList = new ArrayList<>();
theList.add(1);
theList.add(2);
theList.add(3);
theList.add(4);
theList.add(5);
theList.add(6);
myForEach(theList, Test::displayInt);
}
}
Quello che sto cercando di fare è passare il metodo displayIntal metodo myForEachusando un riferimento al metodo. Al compilatore produce il seguente errore:
src/test/Test.java:9: error: cannot find symbol
list.forEach(functionToBlock(myFunction));
^
symbol: method functionToBlock(Function<Integer,Void>)
location: class Test
src/test/Test.java:25: error: method myForEach in class Test cannot be applied to given ty
pes;
myForEach(theList, Test::displayInt);
^
required: List<Integer>,Function<Integer,Void>
found: List<Integer>,Test::displayInt
reason: argument mismatch; bad return type in method reference
void cannot be converted to Void
Il compilatore si lamenta di questo void cannot be converted to Void. Non so come specificare il tipo di interfaccia della funzione nella firma in modo myForEachtale che il codice venga compilato. So che potrei semplicemente cambiare il tipo di ritorno di displayIntal Voide poi tornare null. Tuttavia, potrebbero esserci situazioni in cui non è possibile modificare il metodo che voglio passare altrove. C'è un modo semplice per riutilizzarlo displayIntcosì com'è?
Blockstato modificatoConsumernelle ultime versioni dell'API JDK 8