In Java, I am able to combine multiple method handle with each its parameters, like this:
foo( a, bar( 2, b ) )
..by using MethodHandles.collectArguments().
The method handle I get can be called like this :
myHandle.invokeExact( 5, 6 ); // invokes foo(5, bar(2, 6))
But now, I would like to get a Method Handle that dispatches its parameters into the call tree like this:
MethodHandle myHandle = ...; // foo( *x*, bar( 2, *x* ) )
myHandle.invokeExact( 3 ); // replaces x by 3 in both locations
// this call represents 'foo(3, bar(2, 3));'
I cannot wrap my head around about how to do that. Can you help me?
As usual for Java Method Handles, not much interest, so I will give you the answer:
Use MethodHandles::permuteArguments combined with a MethodType::dropPatameterTypes() call.
In my case, it is simply a matter of doing this:
MethodHandle handle = [...]; // method handle representing f(x1, x2) = x1 + (x2 - 2)
MethodHandle h_permute = MethodHandles.permuteArguments(
handle,
handle.type().dropParameterTypes(1, 2), // new handle type with 1 less param
0,
0);
// h_permute now represents f(x) = x + (x - 2)