I am implementing a class to store objects that can be assigned a double value. For this reason, I have created a HasDoubleValue interface, that contains a single method:
public interface HasDoubleValue{
public double doubleValue();
}
My main class is defined as such:
Data <O extends HasDoubleValue> {...}
Now, when I try to initialize this class to store Integers, I get a "type argument Integer is not within bounds of type-variable O" error, although Integer implements the doubleValue() method by default.
I suppose that this happens because Integer does not explicitly implement my HasDoubleValue interface, although it has the method I am looking for. Is this right? What would a natural workaround be?
Yes, it is right. Java doesn't use duck-typing as JavaScript or TypeScript.
A solution is to create an adapter class that wraps a Integer, delegates to it, and actually implement the interface.
Or, since inthis case your interface is a functional interface, to use a lambda or a method reference to create an instance of HasDoubleValue from an Integer.
public interface HasDoubleValue{
double doubleValue();
}
final class IntegerHasDoubleValueAdapter implements HasDoubleValue {
private final Integer i;
public IntegerHasDoubleValueAdapter(Integer i) {
this.i = i;
}
@Override
public double doubleValue() {
return i.doubleValue();
}
}
class Data<O extends HasDoubleValue> {
void put(O o) {}
public static void main(String[] args) {
Integer i = 42;
Data<IntegerHasDoubleValueAdapter> d1 = new Data<>();
d1.put(new IntegerHasDoubleValueAdapter(i));
Data<HasDoubleValue> d2 = new Data<>();
d2.put(() -> i.doubleValue());
Data<HasDoubleValue> d3 = new Data<>();
d3.put(i::doubleValue);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With