As mentioned, it is a common mental model that "Instanceof is the subtype operator", as Remi claims here:

On 9/9/2022 11:35 AM, Remi Forax wrote:
And i'm still worry that we are muddying the water here, instanceof is about instance and subtypining relationship (hence the name)

We will surely elicit some "who moved my cheese" responses when generalizing from "subtyping" to "safe casting precondition" (though the two coincide given the restrictions on instanceof today.)  The question is largely a pedagogical one; how do we help people see that "subtyping operator" is merely a convenient description of what instanceof has done to date?

We made a choice to lump rather than split by having `instanceof` take a pattern on the RHS as well as a type.  This choice is not without its challenges (mostly, the confusion around whether patterns match null or not), but it also illustrates that people can get over a narrow view of what `instanceof` "means", since this has generally not been a problem to date.  The leap from "reference types only" to "all types" is a smaller one, though it appeals to a broader view of polymorphism.

When restricted to reference types, `instanceof` is a question about subtyping relative to inclusion polymorphism.  When we bring in primitive widening/narrowing, we are appealing to coercion polymorphism too -- "can this value be coerced to this type without getting mangled."  When we bring in boxing and unboxing, we appeal to another form of coercion.  (Both forms are covered under existing conversion rules.)  I suspect this direction is not likely to be helpful, since these terms are not particularly widely used in the Java community.

Positioning "instanceof TYPE" as the "precondition for safe casting to TYPE" seems a pretty simple leap to me, since "instanceof TYPE" is basically never seen in the wild when not immediately followed by a cast to the same type.  Which makes sense; casting is risky (unless the type pairs involved are known to be related in a certain way), and instanceof is how you avoid casting surprises.

Is there a better way to explain this?

Reply via email to