Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is AS telling me that `(ob instanceof Button)` is always `false`?

Why is AS telling me that (ob instanceof Button) is always false?

Also, it gives a "hint" to 'Cast to Button'. If I take the hint, nothing changes.

  void setTextSizeForField(int textSize, Object ... obs){
    for(Object ob: obs)
           if (ob instanceof EditText) ((EditText) ob).setTextSize ( textSize );
      else if (ob instanceof TextView) ((TextView) ob).setTextSize ( textSize );
      else if (ob instanceof Button)   ((Button)   ob).setTextSize ( textSize/10 );
  }

The entire text of the message is:

Condition 'ob instanceof Button' is always 'false' less... (Ctrl+F1) 
This inspection analyzes method control and data flow to report possible conditions that are
 always true or false, expressions whose value is statically proven to be constant, and 
situations that can lead to nullability contract violations. 

Variables, method parameters and return values marked as @Nullable or @NotNull are 
treated as nullable (or not-null, respectively) and used during the analysis to check 
nullability contracts, e.g. report possible NullPointerException errors. 

More complex contracts can be defined using @Contract annotation, for example: 
@Contract("_, null -> null") — method returns null if its second argument is null

@Contract("_, null -> null; _, !null -> !null") — 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
The inspection can be configured to use custom @Nullable 

@NotNull annotations (by default the ones from annotations.jar will be used) 

I'm not using annotations.

* EDIT *

If I swap the two else if statements, I get no warning and the code runs fine.

So I guess "never mind" could be in order, but what do you think AS was doing?

like image 722
DSlomer64 Avatar asked Feb 10 '23 00:02

DSlomer64


1 Answers

Documentation shows that Button extends TextView, so that branch will never be taken. If you invert your checks for Button and TextView, then different paths will be taken.

like image 98
Atreys Avatar answered May 16 '23 07:05

Atreys