3

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?

Renato
  • 12,940
  • 3
  • 54
  • 85
  • don't know dart but is this the same question? https://stackoverflow.com/questions/7715948/how-to-perform-runtime-type-checking-in-dart looks like you're asking if type A is type Stream to me – kenny Mar 22 '19 at 22:28
  • That's a different question. I am asking how to check the type a type parameter represents, not the type of a value. – Renato Mar 23 '19 at 07:28

3 Answers3

1

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).

Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • Using `==` does not work because `Stream` is not equal to `Stream`... I cannot create a dummy instance for the same reason: I would need to know the type parameter of the `Stream` which I can't see how to do. – Renato Mar 23 '19 at 07:36
  • What I needed is equivalent to Java's `Stream.class.isAssignableFrom(A)` (if Java had reified generics). – Renato Mar 23 '19 at 07:40
0

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>) { // ... }
  }
Matt C
  • 4,470
  • 5
  • 26
  • 44
0

This should work:

<A>[] is List<Stream>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 26 '22 at 23:58