Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix wrong type checking when using instanceName in combination with generic type parameter #32

Merged
merged 3 commits into from
Nov 22, 2019

Conversation

knaeckeKami
Copy link
Contributor

@knaeckeKami knaeckeKami commented Nov 19, 2019

Currently, this code snippet fails:

import 'package:get_it/get_it.dart';

void main(){
  GetIt.I.registerSingleton<String>("test", instanceName: "instanceName");

  final myString = GetIt.I<String>("instanceName");

  print(myString);
}

with the message:

Unhandled exception:
Invalid argument(s): Object with name instanceName has a different type (String) than the one that is inferred (String) where you call it
#0      GetIt.get (package:get_it/get_it.dart:80:11)
#1      GetIt.call (package:get_it/get_it.dart:98:12)
#2      main (package:neocortex_mobile/get_it_test.dart:9:27)
#3      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

The reason for this is, that the logic for checking the type or the object registered with instanceName is wrong:

 if (registeredObject.registrationType is! T) {
          print(T.toString());
          throw ArgumentError(
              "Object with name $instanceName has a different type (${registeredObject.registrationType.toString()}) than the one that is inferred (${T.toString()}) where you call it");
        }

registeredObject.registrationType is of Type Type and T is of Type String (in this case), so the comparison fails.
This only works if the caller does not use generic type parameters, because then T is of type dynamic, and dynamic is a bottom type, so the X is dynamic is always true.

This PR fixes this by checking the type of the actual instance.
I also added a test for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants