আমি প্রথম শ্রেণির নাগরিক হিসাবে কীভাবে কাজ করে তা জানার জন্য আমি জাভা 8 এর সাথে ঘুরেছি। আমার কাছে নিম্নলিখিত স্নিপেট রয়েছে:
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);
}
}
আমি যা করার চেষ্টা করছি তা হল একটি পদ্ধতি রেফারেন্স ব্যবহার করে displayIntপদ্ধতিতে পাস করা method myForEachসংকলক করতে নিম্নলিখিত ত্রুটি উত্পন্ন করে:
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
সংকলক অভিযোগ করে যে void cannot be converted to Void। myForEachকোড কম্পাইল করে এমন স্বাক্ষরে ফাংশন ইন্টারফেসের ধরণটি কীভাবে নির্দিষ্ট করতে হয় তা আমি জানি না । আমি জানি যে আমি কেবল ফিরে আসার প্রকার পরিবর্তন displayIntকরতে পারি Voidএবং তারপরে ফিরে আসি null। তবে এমন পরিস্থিতি থাকতে পারে যেখানে আমি অন্য কোথাও যে পদ্ধতিতে যেতে চাই তার পদ্ধতিটি পরিবর্তন করা সম্ভব নয়। displayIntএটির মতো পুনঃব্যবহার করার কোনও সহজ উপায় আছে ?
BlockConsumer