为什么计算函数在将 Integer 转换为 double 时不报错?
Why does not compute function give error while converting Integer to double?
为什么下面的代码工作正常并且没有抱怨 return 类型的函数是整数而不是双精度?
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
为什么下面的代码工作正常并且没有抱怨 return 类型的函数是整数而不是双精度?
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