Table of contents
Dart provides the is
and as
operators for checking an object's type at runtime. This is useful when you need to perform different actions based on the actual type of an object.
is
operator
The is
operator allows you to check if an object belongs to a certain type. So, you could use it to check if the toy you picked is a car, a doll, or something else.
as
operator
The "as" operator allows you to safely convert an object to a specific type if you're sure it belongs to that type.
For example, if you've checked that the toy is a car, you can use the "as" operator to treat it as a car and access car-specific properties and methods.
Example:
class Animal {
void makeSound() {
print('Some generic sound');
}
}
class Dog extends Animal {
@override
void makeSound() {
print('Bark! Bark!');
}
void fetch() {
print('Fetching the ball');
}
}
void main() {
Animal myPet = Dog();
if (myPet is Dog) {
// Type check
(myPet as Dog).fetch(); // Type casting
}
myPet.makeSound();
}
In this example, the is operator checks if myPet is of type Dog, and if true, the as operator is used to cast it to the Dog type to access the fetch method.