So i'm trying to pass a Function to perform an operation on a int[x] value.
So this is my method:
public void apply(int index, UnaryOperator<Integer> func) {
V[index] = func.apply(V[index]);
}
This works:
register.apply(0, new UnaryOperator<Integer>() {
@Override
public Integer apply(Integer x) {
return x & 6;
}
});
and this works:
UnaryOperator<Integer> func = x -> x & 6;
register.apply(0, func);
But this gives me a compile error:
register.apply(0, x -> x & 6);
"Operator & can not be applied to java.lang.Object, int"
The compiler doesn't seem to be able to infer the type, even though it is defined in the method declaration UnaryOperator<Integer>
What am i missing? am i blind? or does this just not work in java?
I'm using intellij CE edition 2019.1.2 and OpenJDK 11.0.1 on a macbook.
Oleksandr example:
register.apply(0, (Integer x) -> x & 6);
Does not work, compiler gives me:
incompatible types in lambda expression, Expected Object but found Integer
This does work:
register.apply(0, x -> (x & 6));
By explicitly telling it to perform the bitwise operation first and then return (i still can't explain why this works and not without but now it works)
But the best solution was to use the IntUnaryOperator
interface that i wasn't even aware of suggested by RealSkeptic in the comments above.
public void apply(int index, IntUnaryOperator func) {
V[index] = func.applyAsInt(V[index]);
}
Thanks for your help