JetBrains' @Contract annotation

sponge picture sponge · Jan 5, 2016 · Viewed 23.3k times · Source

How does the org.jetbrains.annotations.Contract annotation work? How does IntelliJ IDEA support it?

Answer

dcsohl picture dcsohl · Jan 5, 2016

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.