为什么下面的代码工作正常并且没有提示函数的返回类型是 Integer 而不是 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);
}
最佳答案
发生这种情况是因为 java 会自动转换类型(如果不会导致精度损失)。它可以将 int 转换为 double,但不能将 double 转换为 int,因为小数部分会丢失(但当然你可以手动完成)。 您可以在这里阅读 https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
关于java - 为什么计算函数在将 Integer 转换为 double 时不给出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60162259/