Skip to content

Instantly share code, notes, and snippets.

@Lambeaux
Last active April 19, 2018 18:37
Show Gist options
  • Save Lambeaux/7d809587b2f3a230a52e51350890b426 to your computer and use it in GitHub Desktop.
Save Lambeaux/7d809587b2f3a230a52e51350890b426 to your computer and use it in GitHub Desktop.
Optionals erase types, even with casting
List<Map> resultTemplates = new ArrayList();
// Will not compile
List<String> descriptors =
Optional.of(resultTemplates.get(0))
.map(m -> m.get("descriptors"))
.map(List.class::cast)
.orElseThrow(() -> new AssertionError("Result template data was malformed"))
.stream()
.map(String.class::cast) // Explicitly ignoring this cast
.collect(Collectors.toList()); // Returning an Object, not a List
@Lambeaux
Copy link
Author

Need to tell the compiler that the data in the optional is a List<?> so raw types are not used automatically.

@Lambeaux
Copy link
Author

Method references cannot transport the type information on their own. Either of these would work:

outsideList
        .stream()
        .findFirst()
        .map((Function<Object, List<?>>) List.class::cast)
        .orElseThrow(RuntimeException::new)
        .stream()
        .map(String.class::cast)
        .collect(Collectors.toList());

Or:

outsideList
        .stream()
        .findFirst()
        .map(l -> (List<?>) l)
        .orElseThrow(RuntimeException::new)
        .stream()
        .map(String.class::cast)
        .collect(Collectors.toList());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment