The following two code examples represent the same logic. Check if the row is null and the branch is based on this check. The first sample compiles safely. The second creates a type mismatch error associated with Java generics. My question seems simple enough, but it eludes me. Why does the compiler treat these two statements differently? How can I better understand what is happening here?
protected Collection<String> getUserRoles(Object context, Set<String> mappableRoles) { String cookieValue = extractCookieValue(context); if (cookieValue != null) { return securityService.getRolesForUser(cookieValue); } else { return Collections.emptySet(); } } protected Collection<String> getUserRoles(Object context, Set<String> mappableRoles) { String cookieValue = extractCookieValue(context); return cookieValue == null ? Collections.emptySet() : securityService.getRolesForUser(cookieValue); }
Compiler error from Eclipse.
Type mismatch: cannot convert from Set<capture#1-of ? extends Object> to Collection<String>
According to the request, the corresponding part of the SecurityService interface is located here.
public interface SecurityService { public Set<String> getRolesForUser(String userId); }
source share