Renato
Renato

Reputation: 13690

How to check if a type parameter is a specific type in Dart?

I have some Dart code where I want to implement special behaviour in case a generic type's parameter is a Stream.

It's something like this:

class MyType<A> {
    A doit() {
        if (A is Stream) // doesn't work!
        else something-else;
    }
}

Is this possible?

Upvotes: 3

Views: 538

Answers (3)

Jimmy Robert
Jimmy Robert

Reputation: 1

This should work:

<A>[] is List<Stream>

Upvotes: 0

Matt C
Matt C

Reputation: 4555

You could normally use A == Stream, but you said in your case, you have Stream<SomeType>.

If type will always be Stream, you can create a dummy instance using the type parameter you have:

class MyType<A> {
  A doit() {
    final instance = Stream<A>();

    if (instance is Stream<SomeType>) { // ... }
    else if (instance is Stream<OtherType>) { // ... }
  }

Upvotes: 0

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76193

You cannot use A is Stream because A is actually a Type instance. However you can use if (A == Stream) or with a dummy instance if (new Stream() is A).

Upvotes: 1

Related Questions