Why is below code working fine and not complaining about return type of Function being an Integer instead of Double?
public static void main(String[] args) {
double principle = 100;
int interestrate = 5;
double amount = compute(principle, x->x*interestrate);
}
public static double compute(double base, Function<Integer, Integer > func){
return func.apply((int)base);
}
It's happened because java automatically converting types if it does not lead to loss of accuracy. It can convert int to double, but not convert double to int because the decimal part will be lost (but of course you can do it manually). You can read about it here https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.