Skip to content

Instantly share code, notes, and snippets.

@philnguyen
Created October 9, 2021 20:36
Show Gist options
  • Save philnguyen/98028779db4c8c3203a66ababdd2dc17 to your computer and use it in GitHub Desktop.
Save philnguyen/98028779db4c8c3203a66ababdd2dc17 to your computer and use it in GitHub Desktop.
Unsound Java
class Test {
interface Supplier<T> { List<T> get(); }
public static void main(String[] args) {
Supplier<String> strs = supplier("foo", "bar");
Supplier<Integer> ints = supplier(1, 2);
mergeSuppliers(Arrays.asList(strs, ints));
String s = strs.get().get(2); // boom!
}
private static void mergeSuppliers(List<Supplier<?>> suppliers) {
mergeLists(suppliers.stream().map(s -> s.get())); // shouldn't type-check, but does
}
private static<T> void mergeLists(Stream<List<T>> listStream) {
List<List<T>> lists = listStream.collect(Collectors.toList());
if (lists.size() >= 2) {
lists.get(0).addAll(lists.get(1));
}
}
private static<T> Supplier<T> supplier(T ... elements) {
List<T> model = new ArrayList<>(Arrays.asList(elements));
return () -> model;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment