Birinci sınıf vatandaş olarak nasıl işlev gördüğünü öğrenmek için Java 8 ile oynuyorum. Şu snippet'e sahibim:
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);
}
}
Ne yapmaya çalışıyorum bir yöntem başvurusu kullanarak yöntem displayIntyöntemi geçmek myForEach. Derleyici aşağıdaki hatayı üretir:
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
Derleyici bundan şikayet ediyor void cannot be converted to Void. myForEachKod derler böylece imzasında işlev arabiriminin türünü belirtmek nasıl bilmiyorum . Ben sadece dönüş türünü değiştirebilir biliyoruz displayIntiçin Voidve daha sonra dönmek null. Ancak, başka bir yere geçmek istediğim yöntemi değiştirmenin mümkün olmadığı durumlar olabilir. Olduğu displayIntgibi yeniden kullanmanın kolay bir yolu var mı ?
Blockiçin değiştirildiConsumer