Zły typ na stosie operandów… używając jdk 8, lambdy z anonimowymi klasami wewnętrznymi zawodzą, dlaczego?
Uruchomienie poniższego kodu powoduje wyświetlenie komunikatu o błędzieBad type on operand stack
.
public static void main(String args[]) {
TransformService transformService = (inputs) -> {
return new ArrayList<String>(3) {{
add("one");
add("two");
add("three");
}};
};
Collection<Integer> inputs = new HashSet<Integer>(2) {{
add(5);
add(7);
}};
Collection<String> results = transformService.transform(inputs);
System.out.println(results.size());
}
public interface TransformService {
Collection<String> transform(Collection<Integer> inputs);
}
Jednak usunięcie inicjalizacji podwójnego nawiasu (anonimowych klas wewnętrznych) w lamdzie pozwala na uruchomienie kodu zgodnie z oczekiwaniami, dlaczego? Poniższe działa:
public class SecondLambda {
public static void main(String args[]) {
TransformService transformService = (inputs) -> {
Collection<String> results = new ArrayList<String>(3);
results.add("one");
results.add("two");
results.add("three");
return results;
};
Collection<Integer> inputs = new HashSet<Integer>(2) {{
add(5);
add(7);
}};
Collection<String> results = transformService.transform(inputs);
System.out.println(results.size());
}
public interface TransformService {
Collection<String> transform(Collection<Integer> inputs);
}
}
Błąd kompilatora? Jest to wersja wczesnego dostępu ...
(To się nie kompiluje, chyba że masz najnowszejdk 8 lambda download.)