Skip to content

Instantly share code, notes, and snippets.

@haberman
Created February 18, 2023 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haberman/cff671cf94e99f93e809a2ecfeed8d20 to your computer and use it in GitHub Desktop.
Save haberman/cff671cf94e99f93e809a2ecfeed8d20 to your computer and use it in GitHub Desktop.
mellow-arc-8120
class Getter<T> {}
T get<T>(Getter<T> getter) {
if (T == int) {
return 42 as T;
} else if (T == String) {
return "the answer to life, the universe, and everything" as T;
}
throw "Unexpected type: ${T.toString()}";
}
void main() {
var intGetter = Getter<int>();
var strGetter = Getter<String>();
// This works:
var intVal = get(intGetter);
print(intVal);
var strVal = get(strGetter);
print(strVal);
// This doesn't work, T is resolved to Object? (the argument
// type of print()).
//
// But that is confusing because we are passing a Getter<int>,
// not a Getter<Object?>.
print(get(intGetter));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment