IntelliJ IDEA 2018.1 Help

@Contract

The @Contract annotation is used for defining a contract that a method must meet. This lets the IDE find problems in methods which call methods that you have annotated. You can use this annotation not only for annotating your own code but also for other existing libraries.

The @Contract annotation has two attributes — value and pure. The value attribute contains clauses describing causal relationship between arguments and the returned value. The pure attribute is intended for methods that do not change the state of their objects, but just return a new value.

A contract is a set of clauses that describe an input and an output. They are separated with the -> symbol: "A -> B". This forms a contract meaning that when you provide A to a method, you will always get B. Clauses in a contract must be separated with the ; (semicolon) symbol. For example:

@Contract("_, null -> null")A method returns null if its second argument is null.
@Contract("_, null -> null; _, !null -> !null")A method returns null if its second argument is null, and not-null otherwise.
@Contract("true -> fail")A typical assertFalse() method which throws an exception if true is passed to it.

Define a contract

  1. Press Alt+Enter on a method, and select Add method contract or Edit method contract.
  2. Configure the contract and apply the changes.
    contract annotation lib1

Syntax

The @Contract annotation value has the following syntax:

contract ::= (clause ‘;’)* clause
clause ::= args ‘->’ effect
args ::= ((arg ‘,’)* arg )?
arg ::= value-constraint
value-constraint ::= ‘_’ | ‘null’ | ‘!null’ | ‘false’ | ‘true’
effect ::= value-constraint | ‘fail’

The constraints are:
_: any value
null: null value
!null: a value statically proved not to be null
true: true boolean value
false: false boolean value
fail: the method throws an exception if arguments meet argument constraints

Last modified: 24 July 2018

See Also