Dart Errors Unhandled

Viewed 37

I'm new in Dart. In the code bellow exception ccures :

void main(){
    dynamic alpha = "String";
    dynamic beta = 12;        
    print("Your code is so "+beta+" "+alpha);
}

Error : type 'int' is not a subtype of type 'String'

Why when we use dynamic keyword to insist on telling the compiler for doing this job it's still got error? "combining string and other types"

1 Answers

When you declare your variable dynamic it does not mean the variable won't have a runtime type. It means the type can change:

dynamic alpha = 'String';
print(alpha.runtimeType); // prints String
alpha = 1;
print(alpha.runtimeType); // prints int

You can't do that with var. With var the compiler will infer the type, and it's fixed after that:

var beta = 'String';
print(beta.runtimeType);
beta = 1; // error: A value of type 'int' can't be assigned to a variable of type 'String'.
print(beta.runtimeType);

When you try to do "Your code is so " + beta you use the + operator of your String with an int paramter: beta.

You can see in the documentation that the + operator of String only accepts a String:

String operator +(String other);

If you wanted to use that operator you would have to convert the int variable to String:

print('Your code is so ' + beta.toString() + ' ' + alpha);

That's not remarkably beautiful. Instead of concatenation try string interpolation:

print('Your code is so $beta $alpha');
Related