Cheshie
Cheshie

Reputation: 2837

Dart operator + doesn't work

I read in http://api.dartlang.org/ that there should be a String operator +

abstract String operator +(String other)

Creates a new string by concatenating this string with other.

For some reason it doesn't work, and Dart says:

"'+' cannot be used for string concatentation".

Have I misunderstood the operator?

Upvotes: 0

Views: 206

Answers (2)

Pixel Elephant
Pixel Elephant

Reputation: 21403

For a while the + operator was removed for String. However, this was brought back recently. Make sure that the Dart Editor/SDK that you are using are up to date.

Generally,there are better options than using the + operator for String concatenation. For variables you can use string interpolation:

var username = 'Jason';
// ...
var msg = 'Hello ${username}';

And for longer Strings concatenation you should use StringBuffer which avoids building the String until you call toString():

StringBuffer sb = new StringBuffer();
sb.write("Hello ");
sb.write(username);
var msg = sb.toString();

Upvotes: 2

Paul Brauner
Paul Brauner

Reputation: 1347

Which version of Dart are you running? This works for me:

$ dart --version
Dart VM version: 0.6.3.3_r24898 (Thu Jul 11 07:47:12 2013) on "linux_x64"
$ cat test.dart 
main() {
  print("a" + "b");
}
$ dart test.dart 
ab

Upvotes: 3

Related Questions