Felix
Felix

Reputation: 1384

Is it possible to implement multiple interfaces in Dart? If so, is it possible to restrict a generic parameter to implement both?

I'm coming from a c# background and still learning Dart. I'm getting confused with Darts inheritance and generics.

My requirement is this:

A base class that has a property "id", call it A.

An interface that defines a method "speak()", call it B.

These two things need to be orthogonal. Some concrete classes will extend A some will implement B and some will have both.

Now.... I want to have a method:

int mymethod<T extends A and also implements B>(T item){
  item.speak();
  return item.id;
};

Is this possible? I'm finding myself having to build chains of inheritance (B extends A) in order to be able to do the generic type parameter constraints. There are not many examples around that go beyond the very simple generics for collections. Can someone point me to an explanation of the inheritance and generics system that will give me a clear conceptual model to work with?

Upvotes: 4

Views: 4253

Answers (1)

Maximilian
Maximilian

Reputation: 541

Implementing multiple interfaces is possible.

Just write class SomeClass implements Interface1, Interface2{...}.

Unfortunately creating a generic that requires multiple interfaces being implemented is not possible, as described here.

Upvotes: 8

Related Questions