[英]Why java do not give error on returning an integer while the return type is long or double?
[英]Why does not compute function give error while converting Integer to 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.