为什么三元运算符在Java中的方法参数中不起作用 [英] Why is the Ternary operator not working inside a method argument in java
本文介绍了为什么三元运算符在Java中的方法参数中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在开发过程中注意到了这一点。
I got this noted in a middle of a development.
为什么三元运算符不能在方法参数中使用?这里显然是 InputStream
或(其他) String
。
Why is the Ternary operator not working inside a method argument? Here it is clearly InputStream
or (else) String
.
class A{
public static boolean opAlpha(InputStream inputStream) {
// Do something
return true;
}
public static boolean opAlpha(String arg) {
// Do something else
return true;
}
public static void main(String[] args) throws Exception {
boolean useIsr = true;
InputStream inputStream = null;
String arg = null;
// boolean isTrue = useIsr ? A.opAlpha(inputStream): A.opAlpha(arg); // This is OK.
boolean isTrue = A.opAlpha(useIsr ? inputStream : arg); // This is not. (Error : The method opAlpha(InputStream) in the type A is not applicable for the arguments (Object))
}
}
推荐答案
表达式 useIsr? inputStream:arg
的类型为 Object
,因为这是 inputStream
( InputStream
)和 arg
( String
)。
The expression useIsr ? inputStream : arg
is of type Object
, since that's the common type of inputStream
(InputStream
) and arg
(String
).
您没有任何 opAlpha
方法接受 Object
。因此出现编译错误。
You don't have any opAlpha
method that accepts an Object
. Hence the compilation error.
这篇关于为什么三元运算符在Java中的方法参数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文