java - 编译器为什么以及如何区别对待这两个条件?

标签 java generics type-inference conditional-operator type-bounds

以下两个代码示例表示相同的逻辑。检查字符串是否为空,并根据该检查进行分支。第一个示例可以安全编译。第二个产生与 Java 泛型相关的类型不匹配错误。我的问题看起来很简单,但它让我难以理解。为什么编译器以不同的方式对待这两个语句?我怎样才能更好地理解这里发生了什么?

/* compiles cleanly */
protected Collection<String> getUserRoles(Object context,
        Set<String> mappableRoles) {
    String cookieValue = extractCookieValue(context);
    if (cookieValue != null) {
        return securityService.getRolesForUser(cookieValue);
    } else {
        return Collections.emptySet();
    }
}


/* produces a compiler error */
protected Collection<String> getUserRoles(Object context,
            Set<String> mappableRoles) {
    String cookieValue = extractCookieValue(context);
    return cookieValue == null ? Collections.emptySet()
            : securityService.getRolesForUser(cookieValue);
}

来自 Eclipse 的编译器错误。

Type mismatch: cannot convert from Set<capture#1-of ? extends Object> to Collection<String>

根据要求,这是 SecurityService 接口(interface)的相关部分。

public interface SecurityService {
    public Set<String> getRolesForUser(String userId);
}

最佳答案

问题应该在于编译器如何解释三元运算符的返回值。你可能想看看 part 15.25 of the JLS或在此question (有点相关,因为它通过自动装箱变得更加复杂,并且它在运行时而不是在编译时抛出错误)。

希望这能让您走上正确的方向。

关于java - 编译器为什么以及如何区别对待这两个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8989101/

相关文章:

java - StringUtils.isBlank() 与 String.isEmpty()

java - java.util.regex.Matcher 中的 group() ?

java - 业务审计日志 - 推荐的库或方法?

c# - Unity 配置和嵌套泛型类型

c# - 匹配任何 IEnumerable<T> 的通用类型参数

c# - 不能使用三元运算符给 Linq 表达式赋值

java - 由于没有更多的 JRE 11 可供下载,如何让 Java 11 运行时环境正常工作?

java - 泛型类型或方法的最左边界是什么意思,为什么选择此策略进行类型删除?

swift - 通用方法导致 "cannot pass immutable value of type AnyObject? as inout argument"

F# 多态类型