Timur Fayzrakhmanov
Timur Fayzrakhmanov

Reputation: 19577

Dart. What the difference between using generic T and Object?

I try to understand what the difference between using Generics and Object. I've already read some answers related to Java (please see https://stackoverflow.com/a/5207175/1349754) and I found the difference quite noticeable - function/method returns (a) Object if we use Object as input argument type and (b) actual type if we use generic T. However Dart has its own behavior and this case it not applicable. Let's see example:

main() {
  // expect Object type
  print((new TestObject()).Pass('string').runtimeType);
  // expect String type
  print((new TestGeneric()).Pass('string').runtimeType);
  // both output String type
}

class TestObject {
  Object Pass(Object element)
    => element;
}

class TestGeneric<T> {
  T Pass(T element)
    => element;
}

I don't have good knowledge of using object-oriented ideology. So please, could anybody explain what the difference of using generics instead of Object base class.

Upvotes: 1

Views: 1075

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76183

Generics allows to avoid many declarations when only types change between several classes. In your example the TestObject class can be removed and replaced with TestGeneric<Object> everywhere TestObject appears.

Your expected output for (new TestObject()).Pass('string').runtimeType is not correct. runtimeType returns the type of the object. Here it is 'string' that is returned and so 'string'.runtimeType is String.

To know the return type of a method you have to use mirrors at runtime or analyzer at build time.

Upvotes: 1

Related Questions