Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart downcasting

I need to make a downcasting in dart. It is possible for example from Object to int, but I'm not being able to do it with my own classes. Am I doing something wrong? or how is the correct way to do it?

class Person {
  final String name;
  final int age;
  Person(this.name, this.age);
}

class CoolPerson extends Person {
  CoolPerson(String name, int age): super(name, age);

  int someFunction() {
    return name.length * age;
  }
}


main() {

Object x = 42; 
int i = x as int;

print('Im $i');  

Person person = Person('Peter', 30);
CoolPerson coolPerson = person as CoolPerson;
  
print('Im ${coolPerson.name}');

}

The result of this code is:
Im 42
Uncaught Error: TypeError: Instance of 'Person': type 'Person' is not a subtype of type 'CoolPerson'

like image 274
Mark Watney Avatar asked Aug 29 '26 05:08

Mark Watney


1 Answers

It would be better to just create a CoolPerson from the start. Otherwise, it's not possible to cast person as CoolPerson;. A workaround would be creating a CoolPerson from person.

Person person = Person('Peter', 30);
CoolPerson coolPerson = CoolPerson(person.name, person.age);
like image 125
Omatt Avatar answered Aug 31 '26 18:08

Omatt