Reputation: 456
If I have a object like this:
class MyClass<K>{...
How I could check type of K? If was a variable was easy, ex:
(myVar is Object)... //true | false
But in my case, this dont works:
(K is Object) // awalys false
Upvotes: 0
Views: 146
Reputation: 17113
You want ==
here. Using is
is for comparing the type of variable, not a literal type.
This will only check if K
is actually Object
if you use K == Object
. If you pass K
as int
for instance, it will not be considered to be an Object
.
Upvotes: 1
Reputation: 71603
I recommend not using ==
for comparison of Type
objects. It only checks exact equality, which might be useful in a few situations, but in plenty of situations you do want a subtype check.
You can get that subtype check using a helper function like:
bool isSubtype<S, T>() => <S>[] is List<T>;
Then you can check either isSubtype<K, Object>
to check if K
is a subtype of Object
(which is true for everything except Null
and types equivalent to Object?
, but that can also be checked like null is! K
), or isSubtype<Object, K>
to check whether K
is a supertype of Object
.
It has the advantage that you can compare to any type, not just types you can write literals for. For example K == List
only works for List<dynamic>
. If you need to check whether K
is a List<int>
, you can do isSubtype<K, List<int>>
.
You can get equivalence of types (mutual subtype), without requiring them to be the same type, by doing isSubtype
in both directions. For example isSubtype<Object?, dynamic>()
and isSubtype<dynamic, Object?>()
are both true, but if K
is Object?
then K == dynamic
is false.
Upvotes: 0