Concatenating string literals in Dart

UPDATE: Dart now supports the + concatenator for string.

Dart supports multiple ways to concatenate strings: string interpolation, the + operator, and adjacent string literals.

It turns out that puzzles arise from the using + to concatenate strings, so the Dart team felt compelled to take a fresh approach. Dart already had string interpolation, which allows you to embed a string within a string:

// String interpolation in Dart
String to = 'Bob';
String msg = "Hello $to";  // Hello Bob

Dart also has multi-line Strings, using triple quotes:

String htmlTemplate = """
<div>
  <p>
    Hello $to.
  </p>
</div>""";

Sometimes, however, you need to deal with very long strings. You can use the + operator to concat long strings, or use adjacent string literals.

// This works
String longMessage = 'This is what you used to do in Dart. ' +
                     'You would use the + operator ' +
                     'to concat strings. Just like we are ' +
                     'doing here, in fact.';

// So does this
String longMessage = 'This is what you used to do in Dart. '
                     'You would use the + operator '
                     'to concat strings. Just like we are '
                     'doing here, in fact.';

Summary

You can concatenate strings with +, adjacent string literals, and string interpolation.

As always, the Dart team is very interested in your comments, please join the mailing list to share your experiences.

Popular posts from this blog

The 29 Healthiest Foods on the Planet

Lists and arrays in Dart

Converting Array to List in Scala