redhead redhead - 29 days ago 10
Java Question

Unknown type for lambda consumer parameter when using generic class

I have a similar code to the one below, and for some reason when I call a method that takes a

Consumer<BigDecimal>
parameter with a lambda, the lambda parameter is of type
Object
instead of
BigDecimal
. That results in "Cannot resolve method" inside lambda if any method of
BigDecimal
lambda param is called. This happens only when the method taking the consumer is in a generic class, however non of the generics are participating in that consumer-taking method.

public class Creator<T> {

private T something;

private Consumer<BigDecimal> consumer;

public Creator(T something) {
this.something = something;
}

public void create(Consumer<BigDecimal> consumer) {
this.consumer = consumer;
}

}

public class Processor {
public void process(Creator creator) {
creator.create(big -> big.abs());
^^^^^-------------------- Cannot resolve method
}
}


If I remove generic param
<T>
from Creator class, it works, even though the generics do not touch the
create()
method

What's wrong with this?

Answer
public void process(Creator creator) {

In this line, you use Creator as a raw type, which basically destroys type inference.

Write, at the very least,

public void process(Creator<?> creator) {