在 Java 中,假设我们有一个带有参数 double a
的函数。如果我传递一个整数作为参数,它会起作用吗? (我的意思是,是否存在隐式转换?)在相反的情况下:如果我有例如一个整数作为参数,我传递一个 double ?
不幸的是,我现在无法编译我的代码,我想检查一下这个断言。 感谢您的关注。
最佳答案
参见 JLS - Section # 5.3有关方法调用转换
的详细信息。
Method invocation contexts allow the use of one of the following:
- an identity conversion (§5.1.1) - a widening primitive conversion (§5.1.2) - a widening reference conversion (§5.1.5) - a boxing conversion (§5.1.7) optionally followed by widening reference conversion - an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
因此,根据规则 # 2,您的第一次调用(int
到 double
)将正常工作。
但是第二次调用(double
到 int
)将给出编译器错误,根据同一部分中进一步引用的语句:-
If the type of the expression cannot be converted to the type of the parameter by a conversion permitted in a method invocation context, then a compile-time error occurs.
关于Java:将具有不同类型的参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13277655/