IntelliJ IDEA 2016.1 Help

@Contract Annotations

In this section:

Syntax of the @Contract annotations

The @Contract annotation has two attributes: value and pure.

The @Contract annotation value has the following syntax:

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

The constraints here are:

_ - any value null - null value !null - a value statically proved to be not-null true - true boolean value false - false boolean value fail - the method throws exception, if the arguments satisfy argument constraints

The pure attribute is intended for the methods that do not change the state of their objects, but just return a new value. This attribute is either false (by default), or true.


Consider the following code:

private static voidprintSorted(){ List <Integer> sorted = Quicksort.sort(null);if(sorted !=null){System.out.println("Sorted array"+ sorted); } }public static<TextendsComparable<T>> List<T> sort(List<T> list) {if(list != null){ List<T> copy = new ArrayList<T>(list); sort(copy);returncopy; }else{returnnull; } }

IntelliJ IDEA doesn't complain, because it doesn't know that a null input yields a null output.

Let's decorate the sort() method with @Contract annotation, specifying that null inputs yield null outputs.


IntelliJ IDEA immediately recognizes that if statement is extraneous, and reports about the condition that is always false:


See Also

Last modified: 13 July 2016