Reputation: 13690
Some not-so-careful colleagues of mine have been passing around Optional
instances and assuming it's safe to call get
on them without calling isPresent
first.
I know... this shouldn't happen, but the type-system won't stop them!!
So, I wanted IntelliJ to do it. Is it possible to configure IntelliJ so that it will warn (or even throw a compiling error) about calling Optional.get()
without first calling Optional.isPresent()
?
Upvotes: 8
Views: 1002
Reputation: 13690
IntelliJ 2016.1 supports this out-of-the-box!
By default, calling get()
without verifying with isPresent()
first will issue a warning, but you can go to the "Inspections" screen and set Optiong.get() without isPresent() check
to have severity "Error" if you prefer.
Upvotes: 3
Reputation: 175
You could use an inspection to flag instances and show you a warning/error. This may be exclusive to ultimate.
To add a custom inspection, follow https://www.jetbrains.com/idea/help/creating-custom-inspections.html, or do this:
To configure the inspection to your question:
Save your changes and run the inspection. (CTRL+Shift+Alt+I, type "Structural Search Inspection"). This should show you all instances of Optional.get().
Edit: In your question you ask if it's possible to get a compilation error. I believe this will strictly depend on how you're building your code. If you add an inspection and set the error level to 'Error', it should fail on Make/Compile but not on a 'mvn install'.
Upvotes: 0