The is
pattern only checks whether an object has a specific subclass type. If you want to check and use the object as a subclass type, use the as
pattern (which is similar to the as
type-casting operator) in a switch
statement to check and cast an object simultaneously. Combine the as
pattern with the let
pattern to bind the cast object to a temporary constant of the more specific type.
Here’s a function called determineMaintenanceRequirements
, which uses the as
pattern in a switch
statement to check and cast a Train
instance as a MaglevTrain
instance if it is of the appropriate subclass type. If the cast succeeds, the let
pattern provides access to the cast instance as a MaglevTrain
instance so that a subclass-specific method can be called. Otherwise, a default case calls the cleanPassengerCars
method, which can be called on any Train
instance.