Home > Software engineering >  Is it possible in Dart to accept parameters that satisfy both types at the same time?
Is it possible in Dart to accept parameters that satisfy both types at the same time?

Time:04-29

I'm new to Dart, and I want to receive only widgets that inherit a specific interface. In other languages, a class that satisfies two interfaces could be passed to a function. But in Dart, I can't find a similar function or Generic even if I search, so I'm asking a question.

class TypeClassA {
  
}

mixin TypeMixInA {
  
}

class TypeClassB extends TypeClassA with TypeMixInA {
  
}

class TypeClassC extends TypeClassA with TypeMixInA {
  
}


void functionA(TypeClassA & TypeMixInA param) { // TypeClassA & TypeMixInA is possible?
  
}

void main() {
  functionA(TypeClassB());
  functionA(TypeClassC());
}

Is there a way to receive two interface (two mixins or two classes, etc.) like functionA in the example above?

CodePudding user response:

No, it's not possible.

If TypeMixInA is only ever mixed-in on top of TypeClassA, then you can add implements TypeClassA on TypeMixInA and just use TypeMixInA as the argument type.

If the two are used independently, that won't fly.

Then you can introduce abstract class TypeClassAWithMixInA implements TypeMixInA, TypeClassA {} and make both TypeClassB and TypeClassC implement TypeClassAWithMixInA.

If you're not the author of TypeClassB or TypeClassC, that also won't work.

At that point, there is nothing you can do in the static type system to request only instances of classes that implement two separate interfaces. The Dart type system does not have intersection types, which is what that would be.

You have to accept one of the types, then dynamically check that it also implements the other type, and throw at run-time if it doesn't.

  •  Tags:  
  • dart
  • Related