java - How to pass Object object in functional interface/lambda call -
so, have piece of code goes like
public static void printstuff(object[] stuffs, function<?, string> func) { for(object stuff : stuffs) { string stringstuff = func.apply(stuff); system.out.println(stringstuff); // or whatever, done string not relevant } // ... this method called arrays of different types, , corresponding func value, example:
printstuff(arrayofclasses, (class<?> c) -> c.getsimplename()); printstuff(arrayofstrings, (string s) -> '"' + s + '"'); printstuff(arrayofobjects, o -> o.tostring()); so need stuffs object[], because first common superclass of different types amongst method's calls.
and on compilation, get:
myclass.java:6: error: incompatible types: object cannot converted cap#1 string stringstuff = func.apply(stuff); ^ cap#1 fresh type-variable: cap#1 extends object capture of ? my guess javac rants parameter give function<?, string> call, type, object, not extend object.
so question is, how can pass object parameter function<?, string>?
i can change interface types <object, string>, breaks others calls (with class[], string[], etc) , imply losing pretty whole point of genericity, wouldn't it?
unless there way change stuffs type <? extends object>[], or generic type, , i'm pretty sure it's not possible.
thanks in advance, folks.
edit:if change method generic one, i.e.:
public static <u> void printstuff(object[] stuffs, function<u, string> func) { i still compilation error :
myclass.java:6: error: method apply in interface function<t,r> cannot applied given types; string stringstuff = func.apply(stuff); ^ required: u found: object reason: argument mismatch; object cannot converted u
one solution use:
public static <t> void printstuff(t[] stuffs, function<t, string> func) { for(t stuff : stuffs) { // ....
Comments
Post a Comment