Tôi đang cố gắng tìm ra lý do tại sao mã này không biên dịch trên JDK 1.8.0_45
:Tại sao ví dụ dòng Java 8 này không biên dịch?
public class Example<E extends Example<E>> {
public List<? extends Example<?>> toExamples(Collection<String> collection) {
return collection.stream()
.map(v -> lookup(v))
.collect(Collectors.toList());
}
public static <E extends Example<E>> E lookup(String value) {
return null;
}
}
Thêm một dàn diễn viên dường như không cần thiết sửa chữa nó:
public class Example<E extends Example<E>> {
public List<? extends Example<?>> toExamples(Collection<String> collection) {
return collection.stream()
.map(v -> (Example<?>) lookup(v))
.collect(Collectors.toList());
}
public static <E extends Example<E>> E lookup(String value) {
return null;
}
}
Đây là lỗi từ trình biên dịch:
Example.java:9: error: incompatible types: inference variable R has incompatible bounds
.collect(Collectors.toList());
^
equality constraints: List<Object>
upper bounds: List<? extends Example<?>>,Object
where R,A,T are type-variables:
R extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
A extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
T extends Object declared in interface Stream
Vì một lý do nào đó, loại trả về lookup()
không được suy ra một cách chính xác cho việc mở rộng Example
.
tò mò, nó có biên dịch trên bất kỳ phiên bản Java 8 nào trước đây không? báo cáo này có vẻ rất liên quan: https://bugs.openjdk.java.net/browse/JDK-8077304 – EpicPandaForce
Thông báo lỗi chính xác mà bạn nhận được là gì? – Jesper
Bạn cũng có thể thay đổi chữ ký tra cứu: 'public static> Ví dụ tra cứu (giá trị chuỗi)' –
assylias