- +
Using string as a number
examples/dart-intro/using_string_as_number.dart
void main() { var a = 23; var b = 19; print(a + b); // 42 var c = "23"; var d = "19"; print(c + d); // 2319 print(a + d); }
42 2319 Unhandled exception: Class 'String' has no instance method '_addFromInteger@0x36924d72'. NoSuchMethodError : method not found: '_addFromInteger@0x36924d72' Receiver: "19" Arguments: [23] #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:42) #1 int.+ (dart:core-patch/integers.dart:16) #2 main (file:///.../examples/intro/using_string_as_number.dart:10:13) #3 _startIsolate.isolateStartHandler (dart:isolate-patch/isolate_patch.dart:190) #4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:93)
If both variables contain numbers, + will added them together as numbers. If they are both strings, + will concatenate them. If we try to add (+) two variables that hold different types, we will get a run-time exception.