Last active
April 19, 2018 18:37
-
-
Save Lambeaux/7d809587b2f3a230a52e51350890b426 to your computer and use it in GitHub Desktop.
Optionals erase types, even with casting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Need to tell the compiler that the data in the optional is a
List<?>
so raw types are not used automatically.