3

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'

Mark Watney
  • 307
  • 5
  • 13
  • 4
    As it says in the stacktrace and in real life, a `Person` is not always a `CoolPerson`. `person` here is just a `Person`. Imagine if `CoolPerson` had an extra constructor parameter, what would casting do then? – Henry Twist May 02 '21 at 02:05
  • 4
    Downcasts are unsafe; that's why they require explicit casts, which is the programmer asserting that the base type is actually an instance of a derived type. When the claim turns out to not be true, you end up with an error at runtime. Your `person` was never an instance of a `CoolPerson`, so the cast fails. If you want it to succeed, you must construct a `CoolPerson` in the first place. – jamesdlin May 02 '21 at 06:32

1 Answers1

1

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);
Omatt
  • 8,564
  • 2
  • 42
  • 144