Create a custom, java.util.Optional like @Contract
The @Contract annotation only works with pure functions, where we can specify the relation between arguments and return value, right?
In that case, how does the contract work for java.util.Optional get() and isPresent() functions? Is it possible for us to create a similar contract?
For example, I have a Result class that holds http responses, data, status codes, messages, etc.
Result<User> userResult = doHttpRequestAndGetUser()
if (userResult.isSuccessAndNotNull()) {
String userId = userResult.getData().getId(); // Intellij will complain here that getData() can be NULL
}
OR
if (userResult.isFailedOrNull()) {
return userResult;
}
String userId = userResult.getData().getId(); // Intellij will complain here that getData() can be NULL
Is there any way to have a Contract that lets Intellij know that if I call getData() in a userResult.isSuccessAndNotNull() block, the data will always be NON-NULL. Similarly, if I called isFailedOrNull() and returned the result, data is now guaranteed to be NON-NULL?
Btw, both those functions check if the data object inside is null or not null.
Please sign in to leave a comment.
Sorry, there's no way to specify this via @Contract annotation yet.