0

I have a Class that have a function like this:

public class Entity{
      public void apply(final Function<Item, Item> function) {}
}

How do make a Call in such method?

Example:

Entity entity = new Entity();
entity.apply( ??? );
Sham Fiorin
  • 403
  • 4
  • 16
  • Why do you have the `apply` method in `Entity` in the first place? If someone has a `Function` object, they don't need the help provided by the `Entity.apply` method, do they? – ernest_k Jan 17 '19 at 18:24
  • This might answer your question: https://stackoverflow.com/a/53219950/779956 – Erik Jan 17 '19 at 18:27

3 Answers3

1

You need to pass a Function<Item, Item> wich is a function that takes an Item and return an Item, imagine you have a method like

class Item {
    Item doThis() {
        return this;
    }
}

You'll be able to do :

Function<Item, Item> fct = itm -> itm.doThis();
entity.apply(fct);

Which is the lambda form of

Function<Item, Item> fct2 = new Function<Item, Item>() {
    @Override
    public Item apply(Item item) {
        return item.doThis();
    }
};
entity.apply(fct);
azro
  • 53,056
  • 7
  • 34
  • 70
1

Might be able to make use of Consumer<?>

public class Entity{
    void consumingMethod(Consumer<Object> consumer) {
        consumer.accept(this::methodToConsume)
    }

    void methodToConsume(Object o){
        ....
    }
}

Object can be replaced with a specific type, I used several types and Object was best for me

DarceVader
  • 98
  • 7
1

You're working with what we call a "generic" in Java. Generics help with polymorphism (as you know) because it can take on different "types" in different contexts depending on what you want those types to be. So in your example, you can pass an Object to the method that contains whatever type you want the Generic to be. Here is an example of what your generic type (Function) might look like as a class:

public class Function<T, I> {

}

Since this type takes the types (T and I) it is essentially a "Map" in Java. Here is how you can create an Object of type Function as an example:

Function<Integer, String> function = new Function<Integer, String>();

And here is how you would pass this object to the function:

apply(function);

Notice that you will likely need to create a constructor in your Function class for the values of the Wrappers that you will want to use for this Generic. And below is what your apply method definition will look like (it doesn't need to be static, I just did this for simplicity as I was creating the pseudo code. It can be an "Instance" (non-static) method as you mentioned):

public static void apply(Function f) {

}
Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27