Skip to main content

Command Palette

Search for a command to run...

Dart Inheritance: Checking an Objects Type at runtime

Updated
1 min read
Dart Inheritance: Checking an Objects Type at runtime

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.

isoperator

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.

asoperator

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.

Dart

Part 39 of 50

I'll be here to provide explanations, examples, and assistance as you explore the depths of Dart programming language. Together, we'll unravel the intricacies of Dart, from its fundamental concepts to

Up next

Dart Inheritance: Type Interface in a Mixed List

In Dart, type interface is a powerful feature that allows you to define a common interface for a group of related classes. When dealing with a mixed list containing objects of different types, you can leverage type checking to ensure that each object...

More from this blog

Flutter Journey with Jinali

141 posts