Strings

Strings are immutable, which is a fancy way of saying that string operations create new strings instead of modifying existing strings. Strings (like numbers) are hashable, meaning that unique objects have unique hash codes to tell them apart. If we assign a variable to a variable holding a string, both will have the hash code because they are the same object.

primitives/strings.dart
 
var​ str1 = ​"foo"​,
 
str2 = str1;
 
str1.hashCode; ​// 596015325
 
str2.hashCode; ​// 596015325

But if we modify the first string, the result will be an entirely new object while the copy continues to point to the original string.

primitives/string_concat.dart
 
str1 = str1 + ​"bar"​;
 
 
str1.hashCode; ​// 961740263
 
str2.hashCode; ​// 596015325

Dart goes out of its way to make working with strings easy. It is possible to create multiline strings by enclosing them in triple quotes.

primitives/strings_triple.dart
 
"""Line #1
 
Line #2
 
Line #3"""​;

In addition to the + string concatenation operator, Dart considers adjacent strings to be concatenated.

primitives/strings_adjacent.dart
 
'foo'​ ​' '​ ​'bar'​; ​// 'foo bar'

This adjacent string convenience even extends to multiline strings.

primitives/strings_adjacent.dart
 
'foo'
 
' '
 
'bar'​; ​// 'foo bar'

Another convenience of Dart strings is the ability to interpolate variables and expressions into them. Dart uses $ to denote variables to be interpolated.

primitives/strings_interpolation.dart
 
var​ name = ​"Bob"​;
 
 
"Howdy, $name"​; ​// "Howdy, Bob"

If there is potential for confusion over where the variable expression ends and the string begins, curly braces can be used with $.

primitives/strings_interpolation.dart
 
var​ comic_book = ​new​ ComicBook(​"Sandman"​);
 
 
"The very excellent ${comic_book.title}!"​;
 
// "The very excellent Sandman!"

Multiline strings and built-in expression interpolation are a huge win for the beleaguered JavaScripter. This effectively eliminates the need for a separate templating library. Templating is built in!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.5