JAVA:在方法重载中使用三元运算符时出现编译器错误

问题描述 投票:0回答:1
String a = "bla"
byte[] b = new byte [10];

method(String arg1, byte[] arg2)
method (byte[] arg1, byte[] arg2)


method (a != null ? a : b, b)

为什么我不能使用三元运算符来使用上述方法?使用 if else 语句效果很好:

if (a != null) {
    method (a, b)
} else {
    method (b, b)
}

我希望可以在方法重载中使用三元运算符。但是出现编译错误。

java methods overloading conditional-operator
1个回答
0
投票

在方法调用中使用三元运算符时会出现编译错误,因为Java的方法重载是在编译时根据提供的参数的数量和类型来解决的。三元运算符引入了歧义,因为像 != null ? 这样的表达式类型。 a : b 和 b 在运行时之前都是未知的,这使得编译器无法决定调用哪个重载方法。 要在这种情况下使用三元运算符,您可以将三元表达式的结果显式转换为所需的类型:

method((a != null ? a : (String) null), b);

但是,请小心,因为如果 a 为 null,则此方法可能会引入 NullPointerException,因为您将 null 转换为 String。

© www.soinside.com 2019 - 2024. All rights reserved.