What Is Dart
What Is Dart
What Is Dart
Dart?
Kathy Walrath & Seth Ladd
What is
San FranciSco, ca
Related Ebooks
JavaScript: The Definitive Guide, 6th edition
By David Flanagan Released: April 2011 Ebook: $39.99
jQuery Mobile
By Jon Reid Released: June 2011 Ebook: $12.99
What is Dart?
What is Dart?
by Kathy Walrath and Seth Ladd
Copyright 2012 OReilly Media, Inc. All rights reserved. Published by OReilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. OReilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected].
March 2012:
First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the OReilly logo are registered trademarks of OReilly Media, Inc. What is Dart? and related trade dress are trademarks of OReilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and OReilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
Table of Contents
What is Dart? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Why Did Google Create Dart? Does the Web Really Need Another Language? Show Me the Code How Can I Play with Dart? How About a Real Editor? Whats New About Dart? Why Does Dart Look so Familiar? What Is in the Dart Platform? Should I Use Dart for My App Today? How Do You Expect People to Use Dart? How Can I Compile to JavaScript? What Libraries Are Available? dart:core dart:html dart:io Show Me More Code Types Generics Manipulating the DOM Isolates Where Can I Learn More? 1 2 2 3 5 6 8 8 8 9 9 10 10 10 11 11 11 12 13 14 15
iii
What is Dart?
Dart is a new language developed by Google thats getting attention in web app circles. We asked Kathy Walrath and Seth Ladd, members of Googles developer relations team, to explain Darts purpose and its applications. Writing a web app can be lots of fun, especially at the beginning when you experience instant gratification: code, reload, repeat. Unfortunately, finishing and maintaining a web app are not so fun. JavaScript is great for small scripts, and it has the performance chops to run large apps. But when a script evolves into a large web app, debugging and modifying that app can be a nightmare, especially when you have a large team. Enter Dart, an open-source project that aims to enable developers to build more complex, highly performant apps for the modern web. Using the Dart language, you can quickly write prototypes that evolve rapidly, and you also have access to advanced tools, reliable libraries, and good software engineering techniques. Even though Dart is young, it already has tools such as Dartboard (which lets you write and run Dart code in your browser) and Dart Editor (which lets you create, modify, and run Dart apps). A recently released SDK contains command-line tools such as a Dart-to-JavaScript compiler (which produces JavaScript that you can put in any modern browser) and a Dart Virtual Machine (the VM, which lets you run Dart code on servers). The latest tool to become available is a build of the Chromium browser, nicknamed Dartium, that contains a built-in Dart VM. (Note: Dart is still changing. This article is correct as of March 2012, but facts might change and links might go bad. For the latest information, see the Dart website.)
Google Docs), so were quite familiar with the challenges of architecting web apps. Weve also written a browser (Chrome) and a JavaScript engine (V8), so weve thought a lot about how to make web apps run faster. Basically, we created Dart because we think itll help bring more great apps to the web, and we think it should be easier to create more complex web applications.
hi.html:
... <h2 id="status"></h2> <script type="application/dart" src="hi.dart"></script> <!-If the browser doesn't have an embedded Dart VM,
2 | What is Dart?
you can compile Dart code to JavaScript. --> <script type="text/javascript" src="hi.dart.js"></script> ...
The => syntax used to implement main() is a nice, compact way to implement a function that evaluates and returns a single expression. Without =>, the implementation of the main() method would look like this:
main() { print(send('hello', 'Seth', 'Bob')); }
In the send() method implementation above, rate is an optional parameter with a default value. That method also illustrates string interpolation at work (${var}). Heres some Dart code thats more object-oriented:
class Point { Point(this.x, this.y); distanceTo(other) { var dx = x - other.x; var dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); } var x, y; } main() { var p = new Point(2, 3); var q = new Point(3, 4); print('distance from p to q = ${p.distanceTo(q)}'); }
This code should look pretty familiar if youve ever used a class-based language.
Change the code as you like, and then click the Run button (at the upper left). Youll see the results of your code in a new area below:
4 | What is Dart?
The URL at the upper right of the Dartboard is a link to the code you just ran. Like most things related to Dart, Dartboard is still changing. For the latest information, see the Dartboard tutorial.
To run any program in Dart Editor, just click the Run button while any item in that programs library is selected. If your program is a web app, Dart Editor launches Dartium (Chromium with an embedded Dart VM) to run the program. When you are ready to ship to production, the Dart Editor can compile it to JavaScript, making your app available to the entire modern web. Dart Editor has several features to help you edit Dart code, and we expect more features soon. As you can see from the screenshot above, Dart Editor highlights Dart syntax. Dart Editor also supports auto-completion, and it can quickly take you to where types and other APIs are declared. You can also get a quick outline of your programs classes, methods, and fields. See the Dart Editor tutorial for download instructions and a walkthrough.
6 | What is Dart?
tools to understand your code. You might not bother with types while youre developing a prototype, but you might add types when youre ready to commit to an implementation. An emerging pattern is to add types to interfaces and method signatures, and omit types inside methods. Snapshots: Currently, browsers need to parse a web apps source code before that app can run. Dart code can be snapshottedall its state and code recorded at a certain point in timewhich can speed up startup considerably. In initial testing, a web app with 54,000 lines of Dart code started up in 640ms without snapshotting. With snapshotting, it started up in 60ms. When your Dart program is running in the Dart VM, it can see significant startup time performance improvements, thanks to snapshots. Isolates: Dart supports concurrent execution by way of isolates, which you can think of as processes without the overhead. Each isolate has its own memory and code, which cant be affected by any other isolate. The only way an isolate can communicate with another isolate is by way of messages. Isolates allow a single app to use multi-core computers effectively. Another use for isolates: running code from different origins in the same page, without compromising security. For more details see Isolates on page 14, below. Interfaces with default implementations: Ignore this one if youve never used a language that features classes and interfaces/protocols. Still here? OK. If you take a look at the Dart libraries, youll notice that they use interfaces in cases where some other languages would use classesfor example, for Date and HashMap. This is possible because a Dart interface can have a default implementationa class (usually private) that is the default way to create objects that implement the interface. For example, even though Stopwatch is an interface, you can call new Stopwatch() to get a default stopwatch implementation. If you look at the API doc or source code, you can see that the default implementation of Stopwatch is a class named StopwatchImplementation. Generics, but easy: Generics have been done before, but theyve been confusing. Dart takes a new approach by designing a generics system thats more understandable. The tradeoff is sacrificing a bit of exactness, but we believe that enabling developers to be more productive trumps ivory-tower language design. For more details see Generics on page 12, below. HTML library: We also took a fresh look at how you should use the HTML DOM. (DOM is short for Document Object Model; its the interface that lets you programmatically update the content, structure, and style of a web page.) By creating a native Dart library (dart:html) to access and manipulate the DOM, we made elements, attributes, and nodes feel natural to work with. More details are in the sections What Libraries Are Available? on page 10 and Manipulating the DOM on page 13.
8 | What is Dart?
// ********** Library dart:coreimpl ************** // ********** Code for NumImplementation ************** NumImplementation = Number; // ********** Code for StringImplementation ************** StringImplementation = String; // ********** Code for _Worker ************** // ********** Code for top level ************** // ********** Library helloworld ************** // ********** Code for HelloWorld ************** function HelloWorld() { } HelloWorld.prototype.yell = function() { return print("hello world!!!!"); } // ********** Code for top level ************** function main() { return new HelloWorld().yell(); } main();
As you can see, the JavaScript code is straightforward. To get the Frog compiler, download the SDK, which is available now in prerelease.
dart:core
The basic APIs that all apps can count on, whether theyre standalone scripts or inside the browser. These APIs let you perform operations such as: display basic text (print()) group objects in collections (Collection, Set, List, Queue) manipulate key-value pairs (Map) specify dates and times (Date, TimeZone, Duration, Stopwatch) use strings (String, Pattern, RegExp) use numbers (num, int, double, Math) return a value before your operation is complete (Future) compare similar objects (Comparable) perform an operation on each item in a multi-item object (Iterable)
dart:html
APIs for producing UIs for web apps. For example:
10 | What is Dart?
get global objects (document, window) find HTML elements (Elements query() and queryAll()) add and remove event handlers (Elements on property) operate on groups of objects using the built-in Dart collection interfaces
For an example of using this library, see the Manipulating the DOM on page 13 section.
dart:io
Server-side APIs for connecting to the outside world. This library is accessible only when the Dart VM is running on the server. Examples: read and write data (InputStream, OutputStream) open and read files (File, Directory) connect to network sockets (Socket) You can see the API documentation at api.dartlang.org. The community has also started porting libraries that you can use. For example, the crypto libraries from Closure have been ported to Dart. For game development, the popular Box2D physics engine has also been ported to Dart.
Types
Up above, we showed this example:
class Point { Point(this.x, this.y); distanceTo(other) { var dx = x - other.x; var dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); } var x, y; } main() { var p = new Point(2, 3); var q = new Point(3, 4); print('distance from p to q = ${p.distanceTo(q)}'); }
You might notice that although the code defines and uses a class, it otherwise has no types. Types are optional in Dart. They dont change the way programs run, but they make the code more understandable by tools (such as debuggers and IDEs) and developers (such as your replacement, when you move on to an even better project). Think of types as annotations or documentation that can help tools and humans understand your intention better and catch bugs earlier. We think a good place to start adding types is method signatures and interfacesthe surface area of your program. As more people are added to your project and more classes are generated, its useful to know what types are used by (and returned from) methods. Heres the previous sample with types added to the API definitions:
class Point { Point(this.x, this.y); num distanceTo(Point other) { var dx = x - other.x; var dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); } num x, y; } main() { var p = new Point(2, 3); var q = new Point(3, 4); print('distance from p to q = ${p.distanceTo(q)}'); }
Notice how we didnt add types to the method body of distanceTo(). An emerging pattern of idiomatic Dart is to use types for method signatures but not method bodies. Method bodies should be small enough to be easily understood, and we expect tools to perform type inference at some point. However, if you prefer to use types everywhere, youre free to change var dx to num dx, and so on.
Generics
If you havent used generic types beforeor maybe even if you haveseeing something like List<E> in the API reference might be a bit scary. Dont worry. Generics in Dart are easy peasy. For example, if you dont care what types of objects are in a List, then you can create a list like this:
new List()
If you know that your list will only have one kind of object in itonly strings, for examplethen you can (but dont have to) declare that when you create the List object:
new List<String>()
12 | What is Dart?
Why bother with the extra ceremony? Specifying what types your collection can hold is a good way to document to both your fellow programmers and your tools what your expectations are. The tools and the runtime can detect bugs early on. (Fact: new List() is shorthand for new List<Dynamic>(). Dynamic is the type used behind the scenes for untyped variables.) Here are examples of how Dart treats different types and untyped collections. If youre familiar with generics in Java, pay close attention to the last two examples.
main() { print(new print(new print(new print(new print(new print(new List() is List<Object>); List() is List<Dynamic>); List<String>() is List<Object>); List<Object>() is! List<String>); // Not all objects are strings List<String>() is! List<int>); // Strings are not ints List<String>() is List); // TRUE! Every list of string is // a list print(new List() is List<String>); // TRUE! It's OK to pass a List // to a method that expects // List<String>
The last two examples highlight Darts covariant generics. Because you will run into untyped Dart code in the wild, the Dart language must allow you to treat an untyped List the same as a typed List, and vice versa. As you may be able to tell from the code above, Darts parameterized types are reified. This means that the generics arent lost at compile time, so Dart truly knows that a List<String> is a list of Strings. For more tips on using generics, see the Generics section of the Optional Types in Dart article. Also see the blog post Generics in Dart, or, Why a JavaScript programmer should care about types.
// Set an attribute. elem.attributes['name'] = 'value'; // Add a child element. elem.elements.add(new Element.tag("p")); // Add a CSS class to each child element. elem.elements.forEach((e) => e.classes.add("important")); }
For more information, read the article Improving the DOM, and browse the dart:html library.
Isolates
Even though Dart is single threaded, you can still take advantage of multi-core machines by using isolates. An isolate provides memory isolation between different parts of a running program. Each isolate can run in a separate thread or process, managed by the Dart VM. Isolates communicate by sending messages through ports. The messages are copied so that an isolate can't change the state of objects that belong to other isolates. To illustrate isolates at work, lets build a simple echo service. First we will define echo(), a function to run in an isolate. Each isolate has a port, which we can use to receive messages. Well reply to the message via the provided reply port. The main() method creates a new isolate for the echo() function with spawnFunction(). Use the SendPort to send messages to the isolate, and listen for any responses using then().
#import('dart:isolate'); echo() { port.receive((msg, reply) => reply.send("Echo: $msg")); } void main() { SendPort sendPort = spawnFunction(echo); sendPort.call("Hello, Dart!").then((response) => print(response)); }
We tested the preceding code on the Dart VM. In JavaScript, isolates compile to web workers so that they can run in separate processes. Isolates are still getting refactored, stay tuned for more updates.
14 | What is Dart?
Dart is getting ready. We encourage you to learn more about Dart, play with Dart in your browser, browse the API docs, enter feature requests and bugs, and join the discussion. Please give it a try. We look forward to your feedback.