-
Notifications
You must be signed in to change notification settings - Fork 205
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
Dart difficult on check Generic Type's type #1997
Comments
As you pointed out,
void main() => test<String>("Hello World");
void test<T>(T obj) {
// Instead of this
if (T is String) print(obj.toLowerCase());
// do this
if (obj is String) print(obj.toLowerCase());
}
void main() {
// instead of
final List<int> value1 = getValue1<int>();
// do this
final value2 = List<int>.from(getValue2());
}
/// Tries to return a properly-typed list.
List<T> getValue1<T>() {
if (T is int) return [0, 1, 2, 3];
else if (T is String) return ["Hello", "World"];
}
/// Doesn't worry about the precise type of the elements.
List<num> getValue2() => [0.0, 1.0, 2.0, 3.0];
Type typeOf<X>() => X;
void test<T>() => print(typeOf<T>() == int);
void main() => test<int>(); To be able to represent a complex type (ie, |
Thank you for the response sir. The real scenario i face this problem is, i implement mtproto which is communication protocol used by Telegram app. |
I need to find the type of the generic type. In which i will use it into some switch case or if else.
But i have difficulty on getting the specified type.
Using '==' and 'is' only return the value false.
The only method i could use is to instantiate some Class to guess the generic type.
And do the if else on that instantiation.
Are there any simplified method to checking the generic type's type?
I simplify the code like this:
The text was updated successfully, but these errors were encountered: