Could you please explain why with the first return type the code can't be compiled?
The message is : Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<String>
.
Is there inserted an explicit cast in the second case ?
public class GenericsTest {
private String getString() {
return null;
}
public List<String> method() {
String someVariable = getString();
//first return type
//return someVariable == null ? Collections.emptyList() : Collections.singletonList(someVariable);
//second return type
if (someVariable == null) {
return Collections.emptyList();
} else {
return Collections.singletonList(someVariable);
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…