Eduardo Yamauchi
Eduardo Yamauchi

Reputation: 849

How compare If the types using Generics are the same?

Suppose I have the class someClass

class someClass<Generics> {}

someClass<int> a = someClass<int>();
someClass<String> b = someClass<String>();
someClass c = someClass();

How I can check if the elements a,b,c are the same type (someClass) ?

is it possible in Dart?

I tried to use runtimeType method, but the types are differents.

Upvotes: 1

Views: 663

Answers (2)

Marcelo Glasberg
Marcelo Glasberg

Reputation: 30919

To check if some object in the format MyObj<T> has an exact generic type T.

bool isOfExactGenericTypeAs(Object? obj) {
  var runtimeTypeStr = obj.runtimeType.toString();
  var pos = runtimeTypeStr.lastIndexOf('<');
  return runtimeType.toString().endsWith('<${runtimeTypeStr.substring(pos + 1)}');
}

To check if some object in the format MyObj<T> has the exact same generic type T of another object:

bool isOfExactGenericTypeAs(Object? obj) {
  var runtimeTypeStr = obj.runtimeType.toString();
  var pos = runtimeTypeStr.lastIndexOf('<');
  return runtimeType.toString().endsWith('<${runtimeTypeStr.substring(pos + 1)}');
}

My package: https://pub.dev/packages/fast_immutable_collections has two extension which lets you use these methods like this:

// True
<int>[1].isOfExactGenericType(int);

// True
<num>[1].isOfExactGenericType(num);

// False
<int>[1].isOfExactGenericType(num);

// False
<num>[1].isOfExactGenericType(int);

// True
<int>[1].isOfExactGenericTypeAs(<int>[1]);

// True
<num>[1].isOfExactGenericTypeAs(<num>[1]);

// False
<num>[1].isOfExactGenericTypeAs(<num>[1]);

// False
<int>[1].isOfExactGenericTypeAs(<num>[1]);

Note: This is, of course, a horrible hack.

Upvotes: 1

Tidder
Tidder

Reputation: 1214

Actually unlike other languages (like Java), Dart does not have type erasure on generics. This means, the objetcs a, b and c in your example are different types.

If you

print(a.runtimeType);
print(b.runtimeType);
print(c.runtimeType);`

you will get

SomeClass<int>
SomeClass<String>
SomeClass<dynamic>

The generic type is not erased at runtime. If you want to check if all objects are of type SomeClass, you could use

print(a is SomeClass);
print(b is SomeClass);
print(c is SomeClass);

This will give you

true
true
true

Upvotes: 3

Related Questions