mrj
mrj

Reputation: 629

Dart: how to override a generic method?

Consider my following base class:

abstract class IChat<Message extends IMessage> {

  String get getId;
  
  List<T> getUsers<T extends IUser>();

}

Now my extended Model looks like this:

class Chat extends IChat<ChatMessage> {
  String id;
  List<ChatUser> members;

  Chat({this.chat, this.members});


  @override
  String get getId => id;

  @override
  List<T> getUsers<T extends IUser>() => members;
  
}

List<T> getUsers<T extends IUser>() => members; throws an error because I return List<ChatUser> instead of List<T>. How do I override the method to make this work? My ChatUser class obviously also extends IUser.

Edit

@jamesdlin gave one solution: @override List<T> getUsers<T extends IUser>() => members.cast<T>(). It is possible without type casting?

Upvotes: 0

Views: 332

Answers (1)

lrn
lrn

Reputation: 71693

First consider what you actually want your classes to do.

It seems like the subclass has a specific type of IUser that it always wants to return, but a generic function takes its type argument per invocation. So, the type should probably be a property of the class, not of the invocation.

Consider:

abstract class IChat<Message extends IMessage> {

  String get getId;
  
  List<IUser> getUsers();
}

class Chat extends IChat<ChatMessage> {
  String id;
  List<ChatUser> members;

  Chat({this.chat, this.members});

  @override
  String get getId => id;

  @override
  List<ChatUser> getUsers() => members;
}

Would that satisfy your needs?

As stylistic comments, your code is very C#-like, and doesn't look like Dart. I'd probably declare the classes as:

abstract class Chat<M extends Message> {
  String get id;
  List<User> get users;
}

class SomeChat extends Chat<ChatMessage> {
  @override
  final String id;
  @override
  List<ChatUser> users;
  // ...
  SomeChat({this.id, List<CharUser> members, ...}) : users = members;
  // ...
}

Upvotes: 2

Related Questions