Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to return extended object without knowting it?

Let’s assume that we have code as below. I would like to copy User object without knowing that he may be agent, and after copy I would like to receive Agent object if he was that object.

My goal would like to be some parsing function inside User so I don’t have to check for object in later use cases.

Is there any way to return Agent object without knowing about it? Or I have to check if its Agent and then use something like this (user as Agent).copyWith(). It would be nice if I could avoid that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance for any help.

class User {
        final String name;
    
        User(this.name);
    }
    
    
    class Agent extends User {
        Agent(super.name);
    }
    
    
    main() {
        final agent = Agent('name');
        runFunction(agent);
    }
    
    void runFunction(User user) {
    
        if(user is Agent) // true
    
        final copiedUser = user.copyWith(name: newName);
    
        if(copiedUser is Agent) // false
    
    }

>Solution :

You can override the copyWith method in Agent to return an object of that type. If the user object in question is an Agent, then a new Agent will be created.

class User {
  final String name;

  User(this.name);
  
  User copyWith({String? name}) => User(name ?? this.name);
}

class Agent extends User {
  Agent(super.name);
  
  @override
  Agent copyWith({String? name}) => Agent(name ?? this.name);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading