Contract for not null return value

Hello, everybody!

Could you explain, why the following contract does not work?

 
private String name;
  
void setName(String name) {
    this.name = null;     // for test
}

@Contract("-> !null")
String getName() {
    return this.name;
}


Thank you!

1 comment
Comment actions Permalink

First, it might well be that setName is never called, or it's never the case that getName is invoked after setName changes this.name to null. That depends on the overall semantics of your program.

For this case, @NotNull looks more appropriate. If you additionally annotate "name" field as @Nullable, there'll be a warning. In general, contracts should primarily be used for pure functions without side effects, to specify relations between the arguments and the return value. So such checks are not implemented for @Contract annotations. If you feel they must be, please file a feature request to https://youtrack.jetbrains.com/issues#newissue

0

Please sign in to leave a comment.