It's fairly simple. I have a field for a list that may or may not be present (but that must be different from null
as non-initialized), but while I can do
List<String> mylist = new ArrayList<>();
I cannot do
Optional<List<String>> mylist = Optional.of(new ArrayList<String>());
because the types don't match. This is unfortunate. I would not like to hard-wire my code to use ArrayList.
Is there a way around this?
I think the error is with your syntax.
This works for me.
Optional<List<String>> mylist = Optional.of(new ArrayList<String>());
Note the change of ; to the end of the line.
The problem was not Java, it was my Maven project setup.
I had this in my pom.xml
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
which Eclipse then dutifully imported as Java Compiler -> JDK Compliance -> 1.7, and rightfully complained.
By setting this to 1.8 my code now compiles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With