Anas
Anas

Reputation: 1073

how do you assign generic type variable to a know type?

Consider that I have a two class and a enum.

one of its class have a parameter as Enum type

enum A { B, C }

class Q {
  
  Q(A a);
  
}

and Another class is of generic type T which take a one parameter as T type in constructor. Question is how do you convert this class's parameter type T into A inside of its own class ?

class C<T> {
  
  T a;
  
  C(this.a);
  
  void getType(){
   if(T == A) Q(a); /* The arugument type 'T' can't be assigned to Parameter type 'A'
                     cause Class Type is still 'T' */    
  }
  
}

This code contain more than 4 enum and each class for its Type. For reproducible purpose, I reduced to one.

Upvotes: 0

Views: 84

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17113

Do an explicit cast to A. Doing a comparison of types like this likely doesn't do implicit type conversion like it would when checking for null in null-safe Dart. Dart isn't able to see that a is actually of type A even with your if statement.

So just do a as A.

class C<T> {
  
  T a;
  
  C(this.a);
  
  void getType(){
   if(T == A) Q(a as A); 
  }
  
}

Upvotes: 1

Related Questions