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

Time:06-25

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.

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
    
    }

CodePudding user response:

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);
}
  • Related