I have this code . The class is generic and when I instantiate it by passing a String Type. The variable becomes a string type. However the statement
if(_val is String){
}
doesnt seem to be true. Any idea why ?
This is the full code:
class foo<T>{
T _val;
QVar()
{
//Read the value from preferences
if(_val is String){
... //Does not come in here!!
}
}
}
a = new foo<String>();
To check whether the object has a certain type, use == operator. Unlike is , it will only return true if compared to an exectly same type, which means comparing it with its super class will return false .
To check if a string contains other string in Dart, call contains() method on this string and pass the other string as argument. contains() method returns returns a boolean value of true if this string contains the other string, or false if the this string does not contain other string.
Dart is a statically typed language which means while declaring a variable, we need to specify what kind of data that variable is going to store. A variable without value has null value by default. There are basically int , double , boolean and string primitive Data Types in Dart.
Instead of
if(T is String)
it should be
if(_val is String)
The is
operator is used as a type-guard at run-time which operates on identifiers (variables). In these cases, compilers, for the most part, will tell you something along the lines of T refers to a type but is being used as a value
.
Note that because you have a type-guard (i.e. if(_val is String)
) the compiler already knows that the type of _val
could only ever be String
inside your if
-block.
Should you need to explicit casting you can have a look at the as
operator in Dart, https://www.dartlang.org/guides/language/language-tour#type-test-operators.
Use .runtimeType
to get the type:
void main() {
var data_types = ["string", 123, 12.031, [], {} ];`
for(var i=0; i<data_types.length; i++){
print(data_types[i].runtimeType);
if (data_types[i].runtimeType == String){
print("-it's a String");
}else if (data_types[i].runtimeType == int){
print("-it's a Int");
}else if (data_types[i].runtimeType == [].runtimeType){
print("-it's a List/Array");
}else if (data_types[i].runtimeType == {}.runtimeType){
print("-it's a Map/Object/Dict");
}else {
print("\n>> See this type is not their .\n");
}
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With