How does the org.jetbrains.annotations.Contract
annotation work? How does IntelliJ IDEA support it?
The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
Press Alt+Enter on a method, and select Add method contract or Edit method contract. Configure the contract and apply the changes.
Enable annotationsRight-click the gutter in the editor or in the Differences Viewer and select Annotate with Git Blame from the context menu. You can assign a custom shortcut to the Annotate command: go to the Keymap page of the IDE settings Ctrl+Alt+S and look for Version Control Systems | Git | Annotate.
First off, I should say that this annotation is only for IDEA to use to check for possible errors. The Java compiler will ignore it almost entirely (it'll be in the compiled artifact but have no effect). Having said that...
The goal of the annotation is to describe a contract that the method will obey, which helps IDEA catch problems in methods that may call this method. The contract in question is a set of semi-colon separated clauses, each of which describes an input and an output that is guaranteed to happen. Cause and effect are separated by ->
, and describe the case that when you provide X to the method, Y will always result. The input is described as a comma-separated list, describing the case of multiple inputs.
Possible inputs are _
(any value), null
, !null
(not-null), false
and true
, and possible outputs adds fail
to this list.
So for example, null -> false
means that, provided a null
input, a false
boolean is the result. null -> false; !null -> true
expands on this to say that null
will always return false
and a non-null
value will always return true, etc. Finally, null -> fail
means the method will throw an exception if you pass it a null value.
For a multiple-argument example, null, !null -> fail
means that, in a two-argument method, if the first argument is null and the second is not null, an exception will be thrown, guaranteed.
If the method does not change the state of the object, but just returns a new value, then you should set pure
to true.
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