0

I've to deal with an external library which accepts Object as Parameter only. A method signature like this: ExternalObj.setValue(Object object)

My Question is why exactly do I need the stupidWrapper below?

public class FuntionTest {

    public class Foo{
    private Object thing;
    public void setObject(Object thing){
        this.thing=thing;
    }
    public void call(){
        ((Function)thing).apply("FOOO");
    }

    public <R,T> Function<R,T> stupidWrapper(Function<R,T> function){
        return function;
    }
}


@Test
public void testFunction(){
    Foo foo = new Foo();
    foo.setObject(
      foo.stupidWrapper(
         (baz) -> { 
                    System.out.println(baz);
                    return null;
                   })); 
    foo.call();
}

Why can't I use the lamba directly?

debe
  • 1
  • 1
  • 1
    You don’t need a wrapper. A type cast will do, i.e. `foo.setObject( (Function,?>)baz -> { System.out.println(baz); return null; });` But, of course, you need to tell the compiler that you want a `Function` instance. Otherwise, how should the compiler know? – Holger Nov 10 '16 at 12:25
  • If you must use `setObject(Object)`, do the cast in `setObject` so that it fails immediately if you pass in the wrong thing. Don't wait until you call `call()`. But to echo Holger, `stupidWrapper` does literally nothing. – Andy Turner Nov 10 '16 at 12:28
  • @Andy Turner: I think, this isn’t important, as that’s only a mockup to represent the external library outside the OP’s control. The external library perhaps does that immediately or accepts multiple possible types. – Holger Nov 10 '16 at 12:29
  • @Holger right, he might have to pass in an `Object`, but the cast should be done immediately, since it is only ever used as a `Function`. – Andy Turner Nov 10 '16 at 12:30
  • @Holger Thanks for the cast hint. – debe Nov 10 '16 at 12:34
  • See also http://stackoverflow.com/questions/29082430/why-can-not-i-assign-method-reference-directly-to-variable-of-object-type and http://stackoverflow.com/questions/32383699/java-8-lambdas-execution – Tunaki Nov 10 '16 at 13:19

0 Answers0