-1

For example, I want to support the following functionality:

FunctionActivator ac = new FunctionActivator();
ac.addFunc("times2", (Double x)->x*2));
ac.addFunc("reverse", (String s)-> new StringBuffer(s).reverse().toString());
Integer res = ac.useFunc("times2", 2); // should be 4

The approach I'm taking is something like that:

Interface F<R,P> {
    R apply(P input);
}

Class FunctionActivator {
    HashSet<String, /*don't know what to put here*/> keyToFunc;
    ...rest of implementation
}

If I want to keep FunctionActivator class non-generic, what type should I put in the hashset value?

sel
  • 483
  • 5
  • 16
  • 2
    How is the code supposed to work after that? Do you `get` some value out of the map and then you try to invoke it passing some argument? How would you determine dynamically which type the argument would have to have in order to call the function with it? Maybe `HashSet>` works for storing the function, retrieving and invoking it will not work without problems though. By the way: no need to declare `F`, just use `Function`. – luk2302 Jul 23 '17 at 14:10

1 Answers1

-1

For me, it works like this :

public class FunctionActivator {

    //Use a HashMap for Key value mapping, Not a HashSet
    private HashMap<String, Function> keyToFunc = new HashMap<>();

    public void addFunc(String name, Function f) {
        keyToFunc.put(name, f);
    }

    public Object useFunc(String name, Object parameter) {
        return keyToFunc.get(name).apply(parameter);
    }
}

And use it like that :

FunctionActivator ac = new FunctionActivator();

Function<Double, Double> doubleDoubleFunction = (Double x) ->x*2;
ac.addFunc("times2",doubleDoubleFunction);
//ac.addFunc("square", (Integer i) -> i*i); //This DOES NOT work, you need to cast to (Function<Integer, Integer>)

ac.addFunc("reverse", (Function<String, String>)(String s)->new StringBuffer(s).reverse().toString());

System.out.println(ac.useFunc("times2",new Double(5.0)));   // Prints 10.0
System.out.println(ac.useFunc("reverse","Hello World"));    // Prints dlroW olleH

Also, you don't need your F interface, since it exist the Function Interface with the same and more methods

HatsuPointerKun
  • 637
  • 1
  • 5
  • 14
  • Related: https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – luk2302 Jul 25 '17 at 15:17
  • @luk2302 I tried to replace usages of raw types by usages of parametrized types ( so i have `private HashMap> keyToFunc = new HashMap<>();`, and `public void addFunc(String name, Function f) { keyToFunc.put(name, f); }` ). And now i get compile errors like this : `incompatible types: Function cannot be converted to Function`. And in some cases ( like generic array creation ), using parameterized types causes compile errors, while using raw types don't, so the "never use raw types in you code" isn't always valid – HatsuPointerKun Jul 25 '17 at 17:26