IntelliJ IDEA 14.0.0 Web 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:

The constraints here are:

_anyvalue nullnullvalue !nullavaluestaticallyprovedtobenot-null truetruebooleanvalue falsefalsebooleanvalue failthemethodthrowsexception,iftheargumentssatisfyargumentconstraints

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.

Example

Consider the following code:

private static void printSorted(){ List <Integer> sorted = Quicksort.sort(null); if (sorted != null){ System.out.println("Sorted array" + sorted); } } public static <T extends Comparable<T>> List<T> sort(List<T> list) { if(list != null){ List<T> copy = new ArrayList<T>(list); sort(copy); return copy; } else { return null; } }

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.

contract_annotation

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

false_condition_inspection

See Also

Last modified: 4 December 2014
comments powered by Disqus