0

I'm coming from C++ and I feel a little bit frustrated and confused. I was googling for help for a while and I still can't find an answer, so I am here.

How in Java can I implement a NavigableMap<String, ?> where at the question mark is an object which can be called with two arguments and then return a value.

I would like it to look like so:

NavigableMap<String, SomeFunctorClass> container;

// I also don't know how to write a lambda thing in java, so it won't work.
// [](double a, double b) -> double { return a + b; } // in C++
container.put("add", (double a, double b) -> { return a + b; });

// Expected to be 10.
double result = container.get("add")(4, 6);
5
  • I think you want to use a BiFunction<Double, Double, Double> Commented Sep 13, 2021 at 16:29
  • It says that a type argument cannot be a primitive :\ Commented Sep 13, 2021 at 16:30
  • Oh, you wrote Double not double. Give me a sec. Commented Sep 13, 2021 at 16:31
  • "I was googling for help for a while and I still can't find any answer" Really? I tried putting java functor into a search engine (not even Google!) and the first result I got was this Stack Overflow question. Does it not answer the question? Commented Sep 13, 2021 at 16:32
  • It still doesn't fix anything. Commented Sep 13, 2021 at 16:33

2 Answers 2

1

The equivalent in java is a BiFunction:

NavigableMap<String, BiFunction<Double, Double, Double>> container;
container.put("add", (a, b) -> a + b);

Note that generics in Java cannot be primitive, so you should use the boxed versions (Double for double, Integer for int etc.)

If you need more than 2 parameters (for example a TriFunction), then you'll need to create your own interface since Java standard library doesn't offer more than that (it's not as extensible as C++).

As for the way of calling it:

// Expected to be 10.
double result = container.get("add").apply(4.0, 6.0);
Sign up to request clarification or add additional context in comments.

Comments

1

The closest thing Java offers out of the box is probably a BiFunction.

You still won't be able to call it directly with () like you'd do on a C++ functor, but you can call its apply method:

NavigableMap<String, BiFunction<Double, Double, Double>> container = new TreeMap<>();
container.put("add", (a, b) -> a + b);
double result = container.get("add").apply(4.0, 6.0);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.